Model constraint reference

Unique constraints

By default, model field unique constraints - whether created with Field.unique, Meta.unique_together or UniqueConstraint - treat NULL values as distinct from each other. That is, you can store multiple documents a NULL value. This is consistent with most SQL databases.

If you wish to only allow one document with a NULL value, use a UniqueConstraint with nulls_distinct set to False.

The MongoDB query planner will use unique constraints to avoid a collection scan for queries of all built-in fields except ArrayField, BinaryField, and JSONField.

Added in version 6.0.2: Support for UniqueConstraint.nulls_distinct was added.

Changed in version 6.0.4: The query planner won’t use unique constraints created using older versions of Django MongoDB Backend to avoid a collection scan. If you have a constraint created using an older version, you’ll need to drop and re-create it if you want to take advantage of the new constraint format.

MongoDB-specific constraints

Some MongoDB-specific constraints, for use on a model’s Meta.constraints option, are available in django_mongodb_backend.constraints.

Embedded field constraints

EmbeddedFieldConstraint

class EmbeddedFieldUniqueConstraint(**kwargs)

Added in version 6.0.2.

Subclass of UniqueConstraint for use on a top-level model in order to add a unique constraint on subfields of embedded model fields.

The fields argument uses dotted paths to reference embedded fields. For examples, see Unique constraints on EmbeddedModelField and Unique constraints on EmbeddedModelArrayField, Unique constraints on PolymorphicEmbeddedModelField, and Unique constraints on PolymorphicEmbeddedModelArrayField.

Changed in version 6.0.3: Support for subfields of polymorphic model fields was added. (In 6.0.2, only subfields of EmbeddedModelField and EmbeddedModelArrayField are supported.)