Why Unique together is not preventing non unique values? - django

In my model combination of 2 fields (company, AM) should be unique
class Vendor_AM(models.Model):
version = IntegerVersionField( )
company = models.ForeignKey(V_Company, on_delete=models.PROTECT)
AM = models.ForeignKey(AM, on_delete=models.PROTECT)
recomendedprice = MoneyField(max_digits=10, decimal_places=2, default_currency='USD')
price = MoneyField(max_digits=10, decimal_places=2, default_currency='USD')
is_active = models.BooleanField(default=True)
def __unicode__(self):
return u'%s %s %s' % ( self.id, self.AM.material.name , self.company.name )
class Meta:
unique_together = (("AM", "company"),)
For this reason, I have it defined in class Meta. But instead of form validation warning, I am getting an error on save. What could be the reason?
IntegrityError at /vendor/manufacture_material/new/1/http://127.0.0.1:8000/vendor/company/company_am_details/1//
columns AM_id, company_id are not unique
UPDATE:
Form:
class Vendor_AMForm(forms.ModelForm):
class Meta:
model = Vendor_AM
fields = [ 'AM','recomendedprice','is_active' ]
I am populating company directly in the view.

A form can only validate on the fields it actually contains. Since you've excluded company from the form, the combination of company and AM can't be validated.

Related

django checkbox select multiple models

Hi I have the following django model:
class Issue(models.Model):
title = models.CharField(max_length=200)
date = models.DateTimeField(auto_now=True)
assignee = models.ForeignKey(User, on_delete=models.CASCADE, related_name='assignee')
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner', null=True, blank=True)
description = models.TextField()
state = models.IntegerField(choices=STATUS_CHOICES, default=1)
priority = models.IntegerField(choices=RELEVANCE_CHOICES, default=2)
expired_date = models.DateField(auto_now=False, null=True, blank=True)
and a form which allow a user to create an Issue instance:
class IssueForm(forms.ModelForm):
class Meta:
model = Issue
fields = ('title', 'description', 'assignee', 'state', 'priority', 'expired_date')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['title'].label = "Titolo"
self.fields['description'].label = "Descrizione"
self.fields['state'].label = "Stato"
self.fields['priority'].label = "Priorità"
self.fields['expired_date'].label = "Termine"
self.fields['expired_date'].widget.attrs.update({'class': 'datepicker'})
self.fields['assignee'] = forms.MultipleChoiceField(
choices=self.fields['assignee'].choices,
widget=forms.CheckboxSelectMultiple,
label=("Assegnatario")
)
def clean(self):
cleaned_data = super().clean()
user_id = [i for i in cleaned_data['assignee']]
cleaned_data['assignee'] = [User.objects.get(id=i) for i in user_id]
return cleaned_data
I render this form and the field assignee is a checkbox.
I would like to be able to choose several assignee for the same issue, but I got an error because the Issue model expect just one User instance
How can I modify my model Issue in order to get more than one user ?
Thanks
you can create a new class and name it Issue_Instance where every Issue Object can have an assignee as a foreign key the problem that the relation is one to many because you have to choose more than one assignee and Django doesn't support the idea of having Array or List of Foreign Keys(I don't know any frame works that do :=) ) so I would suggest creating a new class or make the foreign key relation one-to-many key field read about it it will be very useful to solve your problem

How to display many fields' values with ForeignKey relationship?

Looking for solution of this problem I encountered some similar threads, but referring to older versions of Django/DRF and thus not working in my case.
There are these two models:
class CsdModel(models.Model):
model_id = models.CharField("Item ID", max_length=8, primary_key=True)
name = models.CharField("Item Name", max_length=40)
active = models.BooleanField(default=True)
def __str__(self):
return self.model_id
class CsdListing(models.Model):
model_id = models.ForeignKey(CsdModel, on_delete=models.CASCADE, default=0, related_name='m_id')
name = models.ForeignKey(CsdModel, on_delete=models.CASCADE, default=0, related_name='m_name')
(...)
EDIT: Serializers are defined this way:
class CsdModelSerializer(serializers.ModelSerializer):
model_id = serializers.RegexField(regex='^\w{2}\d{3}$', allow_blank=False)
name = serializers.CharField(min_length=6, max_length=50, allow_blank=False)
class Meta:
model = CsdModel
fields = '__all__'
class CsdListingSerializer(serializers.ModelSerializer):
session_id = serializers.RegexField(regex='^s\d{2}$', allow_blank=False)
def validate_session_id(self, value):
(...)
class Meta:
model = CsdListing
fields = '__all__'
What I'd like to see, is model_id and name from CsdModel displayed inside a form created based on CsdListing model. But instead, the ID is duplicated:
How should I rebuild the model(s) to have both ID and name displayed in the form?
You should have only one foreign key. But the listing serializer should then reference the model as a nested serializer.
class CsdListing(models.Model):
model = models.ForeignKey(CsdModel, on_delete=models.CASCADE, default=0, related_name='listing')
class CsdListingSerializer(serializers.ModelSerializer):
model = CsdModelSerializer()
session_id = serializers.RegexField(regex='^s\d{2}$', allow_blank=False)

Serialize Many to Many Relationship with Extra fields

Please I'm stuck trying to get around this issue. Guess there is something I'm not getting after looking at other similar questions.
I have these models:
class Dish(BaseModel):
class Meta:
verbose_name_plural = 'dishes'
name = models.CharField(_('dish'), max_length=100)
dish_type = models.CharField(_("dish type"), max_length=100)
price = models.PositiveIntegerField(_("price"))
def __str__(self):
return f"{self.name} costs {self.price}"
class Order(BaseModel):
dishes = models.ManyToManyField(Dish, through='DishOrder')
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
discount = models.PositiveIntegerField(_("total discount"), blank=True)
total = models.PositiveIntegerField(_("total"), blank=True)
shipping = models.PositiveIntegerField(_("shipping cost"), blank=True)
grand_total = models.PositiveIntegerField(_("grand total"), blank=True)
country = models.CharField(_('country code'), max_length=2)
def __str__(self):
return f"order from {self.customer} at {self.total}"
def get_absolute_url(self):
return reverse('order-details', kwargs={'pk': self.pk})
class DishOrder(models.Model):
dish = models.ForeignKey(Dish, on_delete=models.CASCADE, related_name='dishes')
order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='dishes')
quantity = models.PositiveIntegerField(_("quantity"))
discount = models.PositiveIntegerField(_("discount"))
price = models.PositiveIntegerField(_('price'))
And the corresponding serializers like so:
class DishOrderSerializer(serializers.ModelSerializer):
class Meta:
model = DishOrder
fields = (
"quantity",
"discount",
"price"
)
class OrderSerializer(serializers.ModelSerializer):
dishes = DishOrderSerializer(source='dish', many=True)
class Meta:
model = Order
fields = (
"id",
"country",
"customer",
"dishes",
"total",
"discount",
"grand_total",
"voucher"
)
So as can be seen, I have a m2m relationship via a through table. However I can't get the serializer to work. This is the error I keep getting:
Got AttributeError when attempting to get a value for field dishes
on serializer OrderSerializer. The serializer field might be named
incorrectly and not match any attribute or key on the Order
instance. Original exception text was: 'Order' object has no attribute
'dish'.
I have been looking through this for some time trying to figure out what the error is. I will appreciate any help
Since you are using related_name='dishes' in model you should use dishes as source to the manytomany objects:
class OrderSerializer(serializers.ModelSerializer):
dishes = DishOrderSerializer(source='dishes', many=True)
or simple:
class OrderSerializer(serializers.ModelSerializer):
dishes = DishOrderSerializer(many=True)
Since source='dishes' redundant in case you named serializer's field dishes also.

Django REST framework, dealing with related fields on creating records

Preliminary note: this is a rather newbie question, though I have not found a sufficient answer on StackOverflow; many similar questions, but not this one. So I am asking a new question.
The problem: I'm having difficulty creating records where one field is a foreign key to an existing record, and I do not know what I'm doing wrong in my code.
In my app there are two models in question, a one-to-many relationship between Company and BalanceSheet:
models:
class Company(models.Model):
cik = models.IntegerField(default=0, unique=True)
symbol = models.CharField(max_length=4, unique=True)
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.symbol
class BalanceSheet(models.Model):
company = models.ForeignKey(Company,
null=True,
on_delete=models.CASCADE,
related_name='balance_sheets',)
date = models.DateField()
profit = models.BigIntegerField()
loss = models.BigIntegerField()
class Meta:
unique_together = (('company', 'date'),)
def __str__(self):
return '%s - %s' % (self.company, self.date)
serializers:
class BalanceSheetSerializer(serializers.ModelSerializer):
company = serializers.StringRelatedField()
class Meta:
model = BalanceSheet
fields = ('company','date','profit','loss')
class CompanySerializer(serializers.ModelSerializer):
class Meta:
model = Company
fields = ('cik', 'symbol', 'name')
Views:
class BalanceSheetCreate(generics.CreateAPIView):
model = BalanceSheet
queryset = BalanceSheet.objects.all()
serializer_class = BalanceSheetSerializer
urls include:
url(r'^(?P<symbol>[A-Z]{1,4})/create-balance-sheet/$', views.BalanceSheetCreate.as_view(),
name='create_balance_sheet'),
To this point, I have zero problem reading data. However, when trying to create records, I get errors I don't understand:
curl http://localhost:8000/financials/AAPL/create-balance-sheet/ -X POST -d "company=AAPL&date=1968-04-17&profit=1&loss=1"
IntegrityError at /financials/AAPL/create-balance-sheet/
null value in column "company_id" violates not-null constraint
Dropping the company data from that curl command results in the same error.
How do I get around this error? I thought I was telling the api what company I'm interested in, both explicitly in the url and in the post data.
Using python3.6, django 1.11, and djangorestframework 3.7.7
You get the IntegrityError because your code will try to create a new BalanceSheet without a company. That's because StringRelatedField is read-only (see docs) and therefore it's not parsed when BalanceSheetSerializer is used in write mode.
SlugRelatedField is what you need here:
class BalanceSheetSerializer(serializers.ModelSerializer):
company = serializers.SlugRelatedField(slug_field='symbol')
class Meta:
model = BalanceSheet
fields = ('company','date','profit','loss')
To answer my own question, here's what I wound up with. Thanks again go to dukebody.
models:
class Company(models.Model):
cik = models.IntegerField(default=0)
symbol = models.CharField(max_length=4)
name = models.CharField(max_length=255)
def __str__(self):
return self.symbol
class BalanceSheet(models.Model):
company = models.ForeignKey(Company,
null=True,
on_delete=models.CASCADE,
related_name='balance_sheets',)
date = models.DateField()
profit = models.BigIntegerField()
loss = models.BigIntegerField()
class Meta:
unique_together = (('company', 'date'),)
def __str__(self):
return '%s - %s' % (self.company, self.date)
serializers:
class CompanySerializer(serializers.ModelSerializer):
class Meta:
model = Company
fields = ('cik', 'symbol', 'name')
class BalanceSheetSerializer(serializers.ModelSerializer):
company = CompanySerializer(many=False)
class Meta:
model = BalanceSheet
fields = ('company', 'date', 'profit', 'loss')
def create(self, validated_data):
company_data = validated_data['company']
company, created = Company.objects.get_or_create(**company_data)
validated_data['company'] = company
sheet = BalanceSheet.objects.create(**validated_data)
return sheet
I also had to include the full company data within my curl statement as a nested dict.

Django Rest Framework: serializing/deserializing a calculated field

I just started using Django & Django REST framework. I have the following models:
class Account(models.Model):
name = models.CharField(max_length=100, blank=False)
vat_perc = models.DecimalField(max_digits=4, decimal_places=2)
def __str__(self):
return "ACCOUNT: {0} -- {1}".format(self.name, str(self.vat_perc))
class Entry(models.Model):
account = models.ForeignKey(Account)
description = models.CharField(max_length=100)
taxable_income = models.DecimalField(max_digits=10, decimal_places=2)
total_amount = models.DecimalField(max_digits=10, decimal_places=2, null=True)
def save(self, *args, **kwargs):
selected_vat = Account.objects.get(pk=self.account).vat_perc
self.total_amount = self.taxable_income * (100.00+selected_vat)/100.00
super(Entry, self).save(*args, **kwargs)
The idea would be to read the vat_perc value inside the account record the user has just selected and to perform a calculation to determine the total_amount value which then should be saved in the entry record on the database (I know some would regard this as suboptimal due to the duplication of data in the database; please follow me anyway).
The total_amount field should be regularly serialized when requested. Instead, the serializer should not do anything for deserialization, because the overriding of the save method in the model takes care of updating values if a creation or modification occurs. If I get the documentation correctly, all this means setting the total_amount field in the serializer class as read_only.
Now, these are my serializers:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'name', 'vat_perc',)
class EntrySerializer(serializers.ModelSerializer):
class Meta:
model = Entry
fields = ('id', 'account', 'description', 'taxable_income', 'total_amount',)
total_amount = serializers.ReadOnlyField()
# alternatively: total_amount = serializers.FloatField(read_only=True)
But this is the error I get:
Got a TypeError when calling Entry.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Entry.objects.create(). You may need to make the field read-only, or override the EntrySerializer.create() method to handle this correctly.
Original exception text was: int() argument must be a string, a bytes-like object or a number, not 'Account'.
The last sentence sounds particularly obscure to me. Am I getting something wrong? Any hint?
Thanks in advance.
Thanks to Claudiu. Used SlugRelatedField in the serializer class and decimal.Decimaltype instead of float as I did mistankenly. The following code now works:
class Account(models.Model):
name = models.CharField(max_length=100, blank=False)
vat_perc = models.DecimalField(max_digits=4, decimal_places=2)
def __str__(self):
return "ACCOUNT: {0} -- {1}".format(self.name, str(self.vat_perc))
class Entry(models.Model):
account = models.ForeignKey(Account)
description = models.CharField(max_length=100)
taxable_income = models.DecimalField(max_digits=10, decimal_places=2)
total_amount = models.DecimalField(max_digits=10, decimal_places=2, null=True)
def save(self, *args, **kwargs):
self.total_amount = self.taxable_income * (decimal.Decimal(100.00) + self.account.vat_perc) / decimal.Decimal(100.00)
super(Entry, self).save(*args, **kwargs)
serializers.py
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'name', 'vat_perc',)
class EntrySerializer(serializers.ModelSerializer):
class Meta:
model = Entry
fields = ('id', 'account', 'description', 'taxable_income', 'total_amount',)
total_amount = serializers.ReadOnlyField()
account = serializers.SlugRelatedField(queryset=Account.objects.all(), slug_field="vat_perc")