Opened 3 years ago
Closed 3 years ago
#32932 closed New feature (duplicate)
Unique indexes
Reported by: | David Sanders | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 3.2 |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
Django already supports both unique constraints and indexes from the models Meta <3
A worthwhile addition would be to support _unique indexes_, if the database makes this distinction.
In Postgres a unique index is a distinct feature from unique constraints; unique indexes are the mechanism that enforces the unique constraints declared for the table: https://www.postgresql.org/docs/current/indexes-unique.html.
One important difference between the 2 is the fact that indexes may support expressions whereas constraints do not (at least in PG).
An example may be to enforce a unique attribute in a jsonb field:
CREATE UNIQUE INDEX unique_attr ON some_table ( (some_json_field->>'some_attr') )
This could perhaps be a new option on the Index
class:
class SomeTable(models.Model): some_json_field = models.JSONField() class Meta: indexes = ( models.Index(models.RawSQL("some_json_field->>'some_attr'", params=[]), name="unique_attr", unique=True), )
Django 4.0 will support functional unique constraints which are implemented internally by unique indexes, see #30916 and 3aa545281e0c0f9fac93753e3769df9e0334dbaa. I don't think there is a need for a new API.
Duplicate of #30916.