Search code examples
djangodjango-validation

django- IntegrityError - duplicate key value violates unique constraint after adding clean() method


I have the following model.

FRONT_BACK=(('F','Front'), ('B','Back'), ('C','Common'))
PRODUCT_TYPE=(('TL','Tubeless Tyre'), ('TT','Tubed Tyre'), ('NA','Not applicable'))

class Product(models.Model):
    product_group=models.ForeignKey('productgroup.ProductGroup', null=False,blank=False)
    manufacturer=models.ForeignKey(Manufacturer, null=False,blank=False)
    product_type=models.CharField(max_length=2, choices=PRODUCT_TYPE, null=False,blank=False)
    wheel_position=models.CharField(max_length=1, choices=FRONT_BACK, null=False,blank=False)
    opening_stock=models.PositiveIntegerField(default=0)
    stock_in=models.PositiveIntegerField(verbose_name="Stock in so far", default=0)
    stock_out=models.PositiveIntegerField(verbose_name="Stock out so far", default=0)
    created_by=models.ForeignKey(auth.models.User, default=1)

    class Meta:
        ordering=['product_group','manufacturer']
        unique_together = ('product_group', 'manufacturer','product_type','wheel_position')

The unique_together gives the desired result - when I try to duplicate, I get the message

Product with this Product group, Manufacturer, Product type and Wheel position already exists. -----message(1)

In a combination of (ProductGroup,Manufacturer,ProductType), if a product having product_type NA is present, the system should not permit to add another product with TL or TT for the same (ProductGroup,Manufacturer). Similarly, if a product of type TL/TT is present, an addition of NA (with other values the same) should be prevented.

In a combination of (ProductGroup,Manufacturer,ProductType,WheelPosition), if a product having wheel_position C is present, the system should not permit to add another product with F or B for the same (ProductGroup,Manufacturer,ProductType). Similarly if a product of type F/B is present, and addition of C (with other values the same) should be prevented.

In order to ensure this, I've added a clean() method to my form (which is enclosed below). I think this addition does the desired job however, when the unique_key error occurs, instead of displaying the error message by the form, I get an uncaught integrity error.

IntegrityError at /product/create/1/

duplicate key value violates unique constraint "product_product_product_group_id_manufac_485329c6_uniq" DETAIL: Key (product_group_id, manufacturer_id, product_type, wheel_position)=(1, 1, NA, F) already exists.

def clean(self):
        print(self.cleaned_data)
        if self.cleaned_data['product_type'] == 'NA':
            tl=f=Product.objects.filter(product_group=self.cleaned_data['product_group'],
                                           manufacturer=self.cleaned_data['manufacturer'],
                                          product_type=  'TL')
            tt=f=Product.objects.filter(product_group=self.cleaned_data['product_group'],
                                           manufacturer=self.cleaned_data['manufacturer'],
                                          product_type=  'TT')
            if tl.exists() :    
                url = reverse('product_detail', kwargs={'pk': tl[0].id})
                raise forms.ValidationError({'product_type':
                            [mark_safe("<a href=\"%s\">Product Type: TL </a> exists for this combination. N/A is not allowed" % url)]})
            elif tt.exists():
                url = reverse('product_detail', kwargs={'pk': tt[0].id})
                raise forms.ValidationError({'product_type':
                            [mark_safe("<a href=\"%s\">Product Type: TT </a> exists for this combination. N/A is not allowed" % url)]})
        else:
            na=f=Product.objects.filter(product_group=self.cleaned_data['product_group'],
                                           manufacturer=self.cleaned_data['manufacturer'],
                                          product_type=  'NA')
            if na.exists():
                url = reverse('product_detail', kwargs={'pk': na[0].id})
                raise forms.ValidationError({'product_type':
                            [mark_safe('<a href="%s"> Product type N/A </a> already exists for this combination.' % url) ]})

        if self.cleaned_data['wheel_position'] == 'C':
            f=Product.objects.filter(product_group=self.cleaned_data['product_group'],
                                           manufacturer=self.cleaned_data['manufacturer'],
                                          product_type=  self.cleaned_data['product_type'],
                                    wheel_position='F')
            b=Product.objects.filter(product_group=self.cleaned_data['product_group'],
                                           manufacturer=self.cleaned_data['manufacturer'],
                                          product_type=  self.cleaned_data['product_type'],
                                    wheel_position='B')
            if f.exists() :
                url = reverse('product_detail', kwargs={'pk': f[0].id})
                raise forms.ValidationError({'wheel_position':
                            [mark_safe("<a href=\"%s\">Wheel position: Front</a> exists for this combination. Common is not allowed" % url ) ]})
            elif b.exists():
                url = reverse('product_detail', kwargs={'pk': b[0].id})
                raise forms.ValidationError({'wheel_position':
                            [mark_safe("<a href=\"%s\">Wheel position: Back</a> exists for this combination. Common is not allowed"  % url )]})
        else:
            c=Product.objects.filter(product_group=self.cleaned_data['product_group'],
                                           manufacturer=self.cleaned_data['manufacturer'],
                                          product_type=  self.cleaned_data['product_type'],
                                    wheel_position='C')
            if c.exists():
                url = reverse('product_detail', kwargs={'pk': c[0].id})
                raise forms.ValidationError({'wheel_position':
                            [mark_safe("<a href=\"%s\"> Wheel position: Common </a> exists for this combination." % url)]})

Here's query result.

Product.objects.filter(product_group=1, manufacturer=1,product_type='NA') 
<QuerySet [<Product: 1000.20.16 (CEAT, NA, F)>, 
<Product: 1000.20.16  (CEAT, NA, B)>]>

When I comment the clean() method, the system displays a proper message on unique_key duplication as shown above (---- message 1).

I don't know what I'm missing.

Please help.

Thanks.


Solution

  • You must call super() so that the parent class' clean method runs and checks checks unique constraints.

    def clean(self):
        cleaned_data = super(MyForm, self).clean()
        ...
    

    This should prevent the integrity error.