Ilya Bibik
Ilya Bibik

Reputation: 4114

Why Unique together is not preventing non unique values?

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.

Upvotes: 0

Views: 41

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599510

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.

Upvotes: 1

Related Questions