Update on related fields throws FieldDoesNotExist - django

Import and export work as expected but when i try to reimport the same file (update), i get this error:enter image description here
resources.py
class ArticleResource(resources.ModelResource):
number = fields.Field(column_name="GMC", attribute="number", widget=CharWidget())
name = fields.Field(column_name="Artikelbezeichnung", attribute="name")
intern_name = fields.Field(column_name="Artikelbezeichnung_intern", attribute="intern_name")
brand = fields.Field(column_name="Marke", attribute="brand")
base_label_number = fields.Field(column_name="Grundetikettennummer", attribute="base_label_number")
barcode = fields.Field(column_name="Barcode_Produkt", attribute="barcode")
layers = fields.Field(column_name="Lagen", attribute="layers")
formatclass = fields.Field(
column_name="FCL", attribute="formatclass", widget=ForeignKeyWidget(FormatClass, "number")
)
volume = fields.Field(column_name="Volumen_in_L", attribute="volume", widget=IntegerWidget())
height = fields.Field(column_name="Höhe", attribute="height", widget=IntegerWidget())
width = fields.Field(column_name="Breite", attribute="width", widget=IntegerWidget())
comment = fields.Field(column_name="Bemerkung", attribute="comment")
group_code = fields.Field(
column_name="Grundetikett_A-Code", attribute="group", widget=ArticleGroupWidget(ArticleGroup, "code")
)
group_name = fields.Field(
column_name="Bezeichnung_Grundetikett",
attribute="group",
widget=ForeignKeyWidget(ArticleGroup, "name"),
readonly=True,
)
class Meta:
model = Article
use_bulk = True
use_transactions = True
skip_unchanged = True
report_skipped = True
import_id_fields = ["number"]
exclude = ["id", "group", "packsize"]

Related

Filter queryset for foreign key

I need to filter the books associated with my serie model
My models.py
class Serie(models.Model):
serie = models.CharField(max_length = 255)
author = models.ForeignKey(Author, on_delete = models.CASCADE, null = True)
slug = AutoSlugField(populate_from = 'serie', always_update = True)
class Book(models.Model):
serie = models.ForeignKey(Serie, on_delete = models.CASCADE, null = True)
serie_slug = AutoSlugField(populate_from = 'serie', always_update = True, null = True)
book_title = models.CharField(max_length=200)
slug = AutoSlugField(populate_from = 'book_title', always_update = True, null = True)
resume = RichTextField()
pub_date = models.DateTimeField(auto_now_add = True, null = True)
My views.py
class index(ListView):
model = Serie
template_name = 'serie_book_list.html'
ordering = ['id']
def get_queryset(self, *args, **kwargs):
context = super().get_queryset(*args, **kwargs)
search = self.request.GET.get('buscar', None)
if search:
context = context.filter(
Q(serie__icontains = search) |
Q(author__name__icontains = search) |
Q(Book.objects.filter(book_title__icontains = search))
)
return context
I tried to use this code Q(Book.objects.filter(book_title__icontains = search)), but without success.
Cannot filter against a non-conditional expression.
your filter Q(Book.objects.filter(book_title__icontains = search)) not match any field in Serie
try this:
context = context.filter(
Q(serie__icontains=search) |
Q(author__name__icontains=search) |
Q(book__book_title__icontains=search))
)

How to use update_or_create with defaults argument

I have the model League
class League(models.Model):
league = models.IntegerField(primary_key=True)
league_name = models.CharField(max_length=200)
country_code = models.ForeignKey("Country",null=True, on_delete=models.SET_NULL)
season = models.ForeignKey("Season", null=True,on_delete = models.SET_NULL, to_field = "season")
season_start = models.DateField(null = True) season_end = models.DateField(null = True)
league_logo = models.URLField(null = True) league_flag = models.URLField(null = True)
standings = models.IntegerField(null=True)
is_current = models.IntegerField(null=True)
I created objects from this model. After it i needed to add some additional fields to League model after adding those fields League object became so
class League(models.Model):
league = models.IntegerField(primary_key=True)
league_name = models.CharField(max_length=200)
country_code = models.ForeignKey("Country",null=True, on_delete=models.SET_NULL)
season = models.ForeignKey("Season", null=True,on_delete = models.SET_NULL, to_field = "season")
season_start = models.DateField(null = True) season_end = models.DateField(null = True)
league_logo = models.URLField(null = True) league_flag = models.URLField(null = True)
standings = models.IntegerField(null=True)
is_current = models.IntegerField(null=True)
cover_standings = models.BooleanField(null=True)
cover_fixtures_events = models.BooleanField(null=True)
cover_fixtures_lineups = models.BooleanField(null=True)
cover_fixtures_statistics = models.BooleanField(null=True)
cover_fixtures_players_statistics = models.BooleanField(null=True)
cover_players = models.BooleanField(null=True)
cover_topScorers = models.BooleanField(null=True)
cover_predictions = models.BooleanField(null=True)
cover_odds = models.BooleanField(null=True)
lastModified = models.DateTimeField(auto_now=True)
I did migrations and added these fields to db schema. Now i want to add to these added fields values. I read about
update_or_create method and tried to use it for updating League model objects
leagues_json = json.load(leagues_all)
data_json = leagues_json["api"]["leagues"]
for item in data_json:
league_id = item["league_id"]
league_name = item["name"] country_q =Country.objects.get(country = item["country"])
season = Season.objects.get(season = item["season"])
season_start = item["season_start"]
season_end = item["season_end"]
league_logo = item["logo"]
league_flag = item["flag"]
standings = item["standings"]
is_current = item["is_current"]
coverage_standings = item["coverage"]["standings"]
coverage_fixtures_events = item["coverage"]["fixtures"]["events"]
coverage_fixtures_lineups = item["coverage"]["fixtures"]["lineups"]
coverage_fixtures_statistics = item["coverage"]["fixtures"]["statistics"]
coverage_fixtures_plaers_statistics = item["coverage"]["fixtures"]["players_statistics"]
coverage_players = item["coverage"]["players"]
coverage_topScorers = item["coverage"]["topScorers"]
coverage_predictions = item["coverage"]["predictions"]
coverage_odds = item["coverage"]["odds"]
b = League.objects.update_or_create(league = league_id,
league_name = league_name,
country_code = country_q,season = season,
season_start = season_start,
season_end = season_end,
league_logo = league_logo,
league_flag = league_flag,
standings = standings,
is_current = is_current,
cover_standings = coverage_standings,
cover_fixtures_events = coverage_fixtures_events,
cover_fixtures_lineups = coverage_fixtures_lineups,
cover_fixtures_statistics= coverage_fixtures_statistics,
cover_fixtures_players_statistics = coverage_fixtures_players_statistics,
cover_players= coverage_players,
cover_topScorers = coverage_topScorers,
cover_predictions = coverage_predictions,
cover_odds = coverage_odds)
While i am trying to update objects by above method i get an error
django.db.utils.IntegrityError: duplicate key value violates unique constraint "dataflow_league_pkey"
DETAIL: Key (league)=(1) already exists.
I read about defaults argument of update_or_create method but didn't understand how to useit in my case. Can anyone help me
If you use update_or_create like this, first of all, your code will search the row in db with that all parameters.
I think you want to search league by league id and it works like this
You create the dict by any way of defaults, I just copy your code
defaults = dict(
league_name=league_name,
country_code=country_q,
season=season,
season_start=season_start,
season_end=season_end,
league_logo=league_logo,
league_flag=league_flag,
standings=standings,
is_current=is_current,
cover_standings=coverage_standings,
cover_fixtures_events=coverage_fixtures_events,
cover_fixtures_lineups=coverage_fixtures_lineups,
cover_fixtures_statistics=coverage_fixtures_statistics,
cover_fixtures_players_statistics=coverage_fixtures_players_statistics,
cover_players=coverage_players,
cover_topScorers=coverage_topScorers,
cover_predictions=coverage_predictions,
cover_odds=coverage_odds)
And use this defaults to update or create league with particular id
League.objects.update_or_create(defaults=defaults, league=league_id)
This code will find league with league_id and update it with data which you passed as the defaults parameter
OR
This code will create new league with that id and these params
You can use update_or_create like this
if exist, it return obj and created false
if not exist, it return obj and created true.
obj, created = League.objects.update_or_create(defaults=defaults, league=league_id)

Many to many in django Admin

I want to ask. Can i create multiple view my items in django admin.
I have a many to many relationship, so i created an associative entity. But i can't understand how view this in django admin. Can someone help me.
models.py
from django.db import models
from django.contrib import admin
class Client(models.Model):
f_name = models.CharField(verbose_name = "Фамилия", max_length = 100)
l_name = models.CharField(verbose_name = "Имя", max_length = 100)
m_name = models.CharField(verbose_name = "Отчество", max_length = 100)
phone = models.CharField(verbose_name = "Телефон", max_length = 100)
city = models.CharField(verbose_name = "Город", max_length = 100)
address = models.CharField(verbose_name = "Адрес", max_length = 200)
def __str__(self):
return self.f_name + " " + self.l_name + " (" + self.phone + ")"
class Item(models.Model):
name = models.CharField(verbose_name = "Название", max_length = 100)
TYPE_ITEMS = (
("shirt", "Футболка"),
("shoes", "Обувь"),
("bags", "Рюкзаки и сумки"),
("heads", "Головные уборы"),
("others", "Другое"),
)
type_item = models.CharField(verbose_name = "Тип продукта",
choices = TYPE_ITEMS, max_length = 6,
default = "shirt")
other = models.TextField("другая информация")
color = models.CharField("Цвет(а)", max_length = 100)
cost = models.IntegerField("Стоимость за штуку", default = 0)
is_available_now = models.BooleanField("Есть ли в наличии?",
default = False)
available_count = models.IntegerField("Количество в наличии", default = 0)
photo = models.ImageField("Фото", upload_to = "media")
def __str__(self):
return self.name + " " + self.color + " (" + str(self.cost) + " грн)"
class Order(models.Model):
id_client = models.ForeignKey(Client, null = True, blank = True,
verbose_name = "Клиент")
date_order = models.DateField(verbose_name = "Дата заказа")
date_taken = models.DateField(verbose_name = "Дата получения")
is_paid = models.BooleanField(verbose_name = "Оплачено?", default = False)
is_taken = models.BooleanField(verbose_name = "Получил покупатель?",
default = False)
class Order_item(models.Model):
id_order = models.ForeignKey(Order)
id_item = models.ForeignKey(Item)
admin.py
admin.site.register(Item)
admin.site.register(Order)
admin.site.register(Client)
admin.site.register(Order_item)
If user creates order, how can i view what he buy?
If user in admin selects an order i want to view many items. Can i create this with django admin ?
I have done this job. So this is my code:
admin.py
from django.contrib import admin
from myapp.models import Client, Item, Order, Ordering
class ClientAdmin(admin.ModelAdmin):
list_display = ("f_name", "l_name", "m_name", "phone", "city", "address")
list_filter = ["f_name", "l_name", "city"]
class ItemAdmin(admin.ModelAdmin):
list_display = ("name", "type_item", "color", "cost", "is_available_now",
"available_count")
list_filter = ["name", "type_item", "color", "cost", "available_count"]
class OrderingAdmin(admin.ModelAdmin):
list_display = ("id_order", "id_item", "count_items")
list_filter = ["id_order", "id_item", "count_items"]
class OrderingInline(admin.TabularInline):
model = Ordering
fk_name = "id_order"
max_num = 1
class OrderAdmin(admin.ModelAdmin):
list_display = ("id", "id_client", "date_order", "date_taken", "is_paid",
"is_taken")
list_filter = ["date_order", "date_taken", "is_paid", "is_taken"]
inlines = [
OrderingInline,
]
admin.site.register(Item, ItemAdmin)
admin.site.register(Order, OrderAdmin)
admin.site.register(Client, ClientAdmin)
admin.site.register(Ordering, OrderingAdmin)
And what I take:
Thanks to all)))
Instead of use Order_item class, you should add a items = models.ManyToManyField(Item) field into your current Order class.

Django foreign key is not set and hence unable to save form

I have a simple foreign key relationship between two tables. I am able to save the parent, but am unable to save the child which has a foreign key to the parent. This is what my models look like:
class Product(models.Model):
month_choices = tuple((m,m) for m in calendar.month_abbr[1:])
year_choices = tuple((str(n), str(n)) for n in range(2004, datetime.now().year +2 ))
id = models.AutoField(primary_key = True)
title = models.CharField(max_length = 1024)
product_type = models.ForeignKey(ProductType)
month = models.CharField(max_length =3, choices=month_choices)
year = models.CharField(choices=year_choices, max_length = 4)
project = models.CharField(max_length = 15, null = True, blank = True)
url = models.URLField(null = True, blank = True)
export_to_xsede = models.BooleanField()
#def __str__(self):
# return str(self.id)
class Meta:
db_table = "product"
class ProductResource(models.Model):
CHOICES = (('A','A'),('B','B'),('C','C'),('D','D'),('E','E'))
id = models.AutoField(primary_key = True)
product = models.ForeignKey(Product)
resource = models.CharField(choices=CHOICES, max_length = 15)
And my views:
class PublicationForm(forms.ModelForm):
title = forms.CharField(widget=forms.TextInput(attrs={'size':'70'}),required=False)
url = forms.CharField(widget=forms.TextInput(attrs={'size':'70'}),required=False)
class Meta:
model = Product
class ResourceForm(forms.ModelForm):
resource = forms.MultipleChoiceField(choices=ProductResource.CHOICES, widget = forms.CheckboxSelectMultiple)
class Meta:
model = ProductResource
I save the parent:
saved_publication = publications_form.save()
but am unable to save the resource form:
resource_form = ResourceForm(request.POST, instance = saved_publication)
resource_form.product = saved_publication
resource_form.save()
When I print resource_form.errors, I get:
<ul class="errorlist"><li>product<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
I have no idea why the foreign key is not getting set in this case.
I'm assuming you do not want to display the product field on the form, so you should exclude it from the form so the validation will pass:
class ResourceForm(forms.ModelForm):
resource = forms.MultipleChoiceField(choices=ProductResource.CHOICES, widget = forms.CheckboxSelectMultiple)
class Meta:
model = ProductResource
exclude = ['product']
Then in the view, just set the product manually after calling is_valid(). Just be sure to pass commit=False on the form.save() so that it will not actually save to the database until after you set the product. For example
...
saved_publication = publications_form.save()
resource_form = ResourceForm(request.POST)
if resource_form.is_valid():
resource = resource_form.save(commit=False)
resource.product = saved_publication
resource.save()

Django form validation is failing

form.is_valid is always set to false in the below code. How do I implement the code to check why its false.
I have given the code to forms.py, model.py and views.py below.
forms defines the form
views processes the form
model defined the model
forms.py
class VolunteerForm(forms.ModelForm):
volposition = forms.CharField(label="VolunteerPosition",widget=forms.Textarea(attrs={'cols':30,'rows':1}))
roledesc = forms.CharField(label="Role Description",widget=forms.Textarea(attrs={'cols':30,'rows':5}))
noofhours = forms.CharField(widget=forms.Select(choices=NO_OF_HRS_MONTH),max_length=2)
Qualreqt = forms.CharField(label="Qualifications and Requirements",widget=forms.Textarea(attrs={'cols':30,'rows':5}))
Duration = forms.CharField(widget=forms.Select(choices=NO_OF_HRS),max_length=2)
Durationyrmon = forms.CharField(widget=forms.Select(choices=YR_MONTH),max_length=10)
posstatus = forms.CharField(widget=forms.Select(choices=POS_STATUS),max_length=1)
teamrelation = forms.CharField(max_length=50)
class Meta:
model = Volunteer
views.py
def volunteersignupform_2_model(form):
if not form.is_valid():
return None
data = form.cleaned_data
signup = Contact(email=data['email'],
phone=data['phone'],
first_name=data['first_name'],
last_name=data['last_name'],
location=data['location'],
other_location=data['other_location'],
new_ac=data['new_ac'],
int_volunteer=data['int_volunteer'],
int_projects=data['int_projects'],
int_fundraise=data['int_fundraise'],
int_it=data['int_it'],
int_programs=data['int_programs'],
int_marketing=data['int_marketing'],
age=data['age'],
occupation=data['occupation'],
intro_source=data['intro_source'],
comments=data['comments'])
signup.save()
# The next line is needed for signup.get_location_display() function to
# work
signup = Contact.objects.get(id=signup.id)
return signup
models.py
NO_OF_HRS = (
('1','1'),
('2','2'),
('3','3'),
('4','4'),
('5','5'),
('6','6'),
('7','7'),
('8','8'),
('9','9'),
('10','10'),
('11','11'),
('12','12'),
)
YR_MONTH = (
("Y", "Year"),
("M", "Month"),
)
POS_STATUS = (
("A", "Active"),
("C", "Closed"),
)
NO_OF_HRS_MONTH = (
("10","10"),
("20","20"),
("30","30"),
("40","40"),
("50","50"),
("60","60"),
("70","70"),
("80","80"),
("90","90"),
)
class Volunteer(models.Model):
datecreated = models.DateTimeField()
volposition = models.CharField(max_length=100)
roledesc = models.CharField(max_length=400)
noofhours = models.CharField(choices=NO_OF_HRS_MONTH,max_length=2)
Qualreqt = models.CharField(max_length=500)
Duration = models.CharField(choices=NO_OF_HRS,max_length=2)
Durationyrmon = models.CharField(choices=YR_MONTH,max_length=10)
posstatus = models.CharField(choices=POS_STATUS,max_length=1)
teamrelation = models.CharField(max_length=50)