[Django]-Django Model validate_unique method don't raise ValidationError

2👍

Thanks all to help me find out my problem. My code was correct but I made a mistake in query. I am getting canteen_id value by assigning a variable CANTEEN_ID in settings.py and save it by save() method.
So, My query should be:

from projectdir.settings import CANTEEN_ID
def validate_unique(self,exclude=None):    
    qs = Inventory.objects.filter(canteen_id=CANTEEN_ID)

4👍

If you override validate_unique method in your model you should call super as you do in save/delete etc.

def validate_unique(self, exclude=None):
    # custom logic
    super(Inventory, self).validate_unique(exclude=exclude)
👤alTus

2👍

Firstly, I think unique_together should work with a one to one field. If you can create a simple test case that shows that it doesn’t, then it would be worth creating a bug report.

If you do want to check the unique constraint manually, don’t do it in the save() method. The Django admin doesn’t expect a validation error to be raised in the save method, so you get the error. Instead, override the model’s clean method, and do the check in. Model forms, including the ones in the Django admin, will call the clean method when processing the form data.

class Inventory(models.Model):
    ...
    def clean(self):
        qs = Inventory.objects.filter(canteen_id=self.canteen_id)
        if self.pk is None:
            if qs.filter(item=self.item).exists():
            raise ValidationError("item already exists")

See the docs on validating objects for more info.

0👍

The way CANTEEN_ID is provided for save method may hide solution.

Leave a comment