[Fixed]-Django: All IntegerField in a single instance of a model must be unique to one another

1👍

You need to define unique_together in the Meta class of your model.

Sets of field names that, taken together, must be unique.

class ProductPropertiesPriority(SingletonModel):
    ...

    class Meta:
        # set of fields that must be unique together
        unique_together = (('product_type', 'style', 'color', `series`, `size`, 'brand'),)

Django will ensure that the tuple of tuple defined in unique_together option must be unique when considered together. It will be used in the Django admin and is enforced at the database level.

EDIT:

The above method will ensure uniqueness among different instances of the model. To ensure the uniqueness among different fields for a particular model instance, you will need to perform model validation.

You can do that by overriding the .clean() method in your model and write your validations there.

Here, in the clean() method, we will get the values of the fields and compare if they are distinct or not. If they are not distinct, then we will raise a validation error. Also, we override the .save() in the model and call the .full_clean() method as this method will call .clean() and few other methods also.

from django.core.exceptions import ValidationError

class ProductPropertiesPriority(SingletonModel):
    ...

    def clean(self, *args, **kwargs):
        """
        Write your custom validation to check for unique values here
        """
        my_unique_fields = ['product_type', 'style', 'color', 'series', 'size', 'brand']
        values = []
        for field in my_unique_fields:
            values.append(getattr(self, field))
        if len(values) != len(my_unique_fields):
            raise ValidationError(_('All the values must be distinct.'))
        super(ProductPropertiesPriority, self).clean(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.full_clean() # call the full_clean() method
        super(ProductPropertiesPriority, self).save(*args, **kwargs)

NOTE: Django, by default does not call the full_clean() method when save() is called (Check this SO link for more details). You will have to call this method yourself.

0👍

One way would be to override clean() in your model, check the fields in this and raise validation error if two or more of them are same.

I can’t say if this is the best way.

Leave a comment