constraints.txt 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. =====================
  2. Constraints reference
  3. =====================
  4. .. module:: django.db.models.constraints
  5. .. currentmodule:: django.db.models
  6. .. versionadded:: 2.2
  7. The classes defined in this module create database constraints. They are added
  8. in the model :attr:`Meta.constraints <django.db.models.Options.constraints>`
  9. option.
  10. .. admonition:: Referencing built-in constraints
  11. Constraints are defined in ``django.db.models.constraints``, but for
  12. convenience they're imported into :mod:`django.db.models`. The standard
  13. convention is to use ``from django.db import models`` and refer to the
  14. constraints as ``models.<Foo>Constraint``.
  15. ``CheckConstraint``
  16. ===================
  17. .. class:: CheckConstraint(*, check, name)
  18. Creates a check constraint in the database.
  19. ``check``
  20. ---------
  21. .. attribute:: CheckConstraint.check
  22. A :class:`Q` object that specifies the check you want the constraint to
  23. enforce.
  24. For example, ``CheckConstraint(check=Q(age__gte=18), name='age_gte_18')``
  25. ensures the age field is never less than 18.
  26. ``name``
  27. --------
  28. .. attribute:: CheckConstraint.name
  29. The name of the constraint.
  30. ``UniqueConstraint``
  31. ====================
  32. .. class:: UniqueConstraint(*, fields, name)
  33. Creates a unique constraint in the database.
  34. ``fields``
  35. ----------
  36. .. attribute:: UniqueConstraint.fields
  37. A list of field names that specifies the unique set of columns you want the
  38. constraint to enforce.
  39. For example, ``UniqueConstraint(fields=['room', 'date'],
  40. name='unique_booking')`` ensures each room can only be booked once for each
  41. date.
  42. ``name``
  43. --------
  44. .. attribute:: UniqueConstraint.name
  45. The name of the constraint.
  46. ``condition``
  47. -------------
  48. .. attribute:: UniqueConstraint.condition
  49. A :class:`Q` object that specifies the condition you want the constraint to
  50. enforce.
  51. For example::
  52. UniqueConstraint(fields=['user'], condition=Q(status='DRAFT'), name='unique_draft_user')
  53. ensures that each user only has one draft.
  54. These conditions have the same database restrictions as
  55. :attr:`Index.condition`.