========================== Model constraint reference ========================== .. _unique-constraints: Unique constraints ================== By default, model field unique constraints - whether created with :attr:`Field.unique `, :attr:`Meta.unique_together ` or :class:`~django.db.models.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 :class:`~django.db.models.UniqueConstraint` with :attr:`~django.db.models.UniqueConstraint.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 :class:`~django_mongodb_backend.fields.ArrayField`, :class:`~django.db.models.BinaryField`, and :class:`~django.db.models.JSONField`. .. versionadded:: 6.0.2 Support for :attr:`UniqueConstraint.nulls_distinct ` was added. .. versionchanged:: 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 ============================ .. module:: django_mongodb_backend.constraints :synopsis: Database constraints for MongoDB. Some MongoDB-specific :doc:`constraints `, for use on a model's :attr:`Meta.constraints` option, are available in ``django_mongodb_backend.constraints``. Embedded field constraints ========================== ``EmbeddedFieldConstraint`` --------------------------- .. class:: EmbeddedFieldUniqueConstraint(**kwargs) .. versionadded:: 6.0.2 Subclass of :class:`~django.db.models.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 :ref:`embedded-model-field-unique-constraints` and :ref:`embedded-model-array-field-unique-constraints`, :ref:`polymorphic-embedded-model-field-unique-constraints`, and :ref:`polymorphic-embedded-model-array-field-unique-constraints`. .. versionchanged:: 6.0.3 Support for subfields of polymorphic model fields was added. (In 6.0.2, only subfields of :class:`~.fields.EmbeddedModelField` and :class:`~.fields.EmbeddedModelArrayField` are supported.)