#37069 assigned Cleanup/optimization

Document that UniqueConstraint may create unique indexes unassociated with actual database constraints

Reported by: Clifford Gama Owned by: Clifford Gama
Component: Documentation Version: dev
Severity: Normal Keywords: unique
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The docs for UniqueConstraint:

Creates a unique constraint in the database.

This is not always true. Depending on the options used, UniqueConstraint may instead create a unique index via CREATE UNIQUE INDEX rather than a database constraint via ALTER TABLE ... ADD CONSTRAINT ... UNIQUE (source).

For example, adding the following constraints to a model with a name field:

constraints = [
    models.UniqueConstraint(models.F("name"), name="unique_name_exp"),
    models.UniqueConstraint(fields=["name"], name="unique_name_field"),
]

produces the following SQL on PostgreSQL:

BEGIN;
-- Create constraint unique_name_exp on model mymodel
CREATE UNIQUE INDEX "unique_name_exp" ON "upref_mymodel" ("name");
-- Create constraint unique_name_field on model mymodel
ALTER TABLE "myapp_mymodel" ADD CONSTRAINT "unique_name_field" UNIQUE ("name");
COMMIT;

See also Allow unique indexes (via UniqueConstraint) to be created/dropped CONCURRENTLY on PostgreSQL where this came up as something of an issue.

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top