Opened 16 months ago
Last modified 16 months ago
#35594 closed Bug
Add support for non-distinct NULL expressions to UniqueConstraint.validate() — at Version 1
| Reported by: | Mark Gensler | Owned by: | |
|---|---|---|---|
| Component: | Database layer (models, ORM) | Version: | 5.0 |
| Severity: | Release blocker | Keywords: | unique constraint nulls_distinct validation expressions |
| Cc: | Simon Charette | Triage Stage: | Ready for checkin |
| Has patch: | yes | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description (last modified by )
Expressions which evaluate to NULL within UniqueConstraint(*expressions, nulls_distinct=False) are still treated as distinct by UniqueConstraint.validate(). This means a ValidationError is not raised when it should be.
Similarly, if the database connection uses interprets_empty_strings_as_nulls this is also ignored by .validate().
Should #35575 be merged, this problem would also extend to any GeneratedField included in UniqueConstraint(fields=[...], nulls_distinct=False).
E.g.
class Book(models.Model):
name = CharField(max_length=255, null=True, blank=True)
class Meta:
constraints = [
UniqueConstraint(F("name"), nulls_distinct=False, name="book_name_null_unique")
]
then
> Book.objects.create(name=None) > book = Book(name=None) > book.full_clean() # Should raise a `ValidationError` but doesn't. > book.save() # The database raises a `UniqueViolation`.
This ticket was raised following discussion in https://github.com/django/django/pull/18356#pullrequestreview-2166340541