[Django]-IntegrityError not raised on None

5👍

Unique together constraint is applied at the database level. Many databases do not compare null values each other and hence, let the insert operations to go in.

You can fix it by overriding clean method in your model. clean method should be used to provide custom validation or to modify field values before saving. Also, note cleanis not invoked when you callsaveon the object. It should be invoked before calling thesave` method.

from django.core.exceptions import ValidationError
class Record(Model):
    def clean(self):
        # check if exists
        if Record.objects.get(type=self.type,
                          code=self.code,
                          group=self.group):
              # raise an exception
              raise ValidationError("Exists")

0👍

1)

try:
    //somthing
except IntegrityError as e:
    print("integrity")
except Exception as e:
    print(e)`

2)Check it

record=Record(type=type_article_structure,
                  code='shoe',
                  group=None)
record.save()

Leave a comment