2
0

composite-primary-key.txt 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. ======================
  2. Composite primary keys
  3. ======================
  4. .. versionadded:: 5.2
  5. In Django, each model has a primary key. By default, this primary key consists
  6. of a single field.
  7. In most cases, a single primary key should suffice. In database design,
  8. however, defining a primary key consisting of multiple fields is sometimes
  9. necessary.
  10. To use a composite primary key, when defining a model set the ``pk`` attribute
  11. to be a :class:`.CompositePrimaryKey`::
  12. class Product(models.Model):
  13. name = models.CharField(max_length=100)
  14. class Order(models.Model):
  15. reference = models.CharField(max_length=20, primary_key=True)
  16. class OrderLineItem(models.Model):
  17. pk = models.CompositePrimaryKey("product_id", "order_id")
  18. product = models.ForeignKey(Product, on_delete=models.CASCADE)
  19. order = models.ForeignKey(Order, on_delete=models.CASCADE)
  20. quantity = models.IntegerField()
  21. This will instruct Django to create a composite primary key
  22. (``PRIMARY KEY (product_id, order_id)``) when creating the table.
  23. A composite primary key is represented by a ``tuple``:
  24. .. code-block:: pycon
  25. >>> product = Product.objects.create(name="apple")
  26. >>> order = Order.objects.create(reference="A755H")
  27. >>> item = OrderLineItem.objects.create(product=product, order=order, quantity=1)
  28. >>> item.pk
  29. (1, "A755H")
  30. You can assign a ``tuple`` to the :attr:`~django.db.models.Model.pk` attribute.
  31. This sets the associated field values:
  32. .. code-block:: pycon
  33. >>> item = OrderLineItem(pk=(2, "B142C"))
  34. >>> item.pk
  35. (2, "B142C")
  36. >>> item.product_id
  37. 2
  38. >>> item.order_id
  39. "B142C"
  40. A composite primary key can also be filtered by a ``tuple``:
  41. .. code-block:: pycon
  42. >>> OrderLineItem.objects.filter(pk=(1, "A755H")).count()
  43. 1
  44. We're still working on composite primary key support for
  45. :ref:`relational fields <cpk-and-relations>`, including
  46. :class:`.GenericForeignKey` fields, and the Django admin. Models with composite
  47. primary keys cannot be registered in the Django admin at this time. You can
  48. expect to see this in future releases.
  49. Migrating to a composite primary key
  50. ====================================
  51. Django doesn't support migrating to, or from, a composite primary key after the
  52. table is created. It also doesn't support adding or removing fields from the
  53. composite primary key.
  54. If you would like to migrate an existing table from a single primary key to a
  55. composite primary key, follow your database backend's instructions to do so.
  56. Once the composite primary key is in place, add the ``CompositePrimaryKey``
  57. field to your model. This allows Django to recognize and handle the composite
  58. primary key appropriately.
  59. While migration operations (e.g. ``AddField``, ``AlterField``) on primary key
  60. fields are not supported, ``makemigrations`` will still detect changes.
  61. In order to avoid errors, it's recommended to apply such migrations with
  62. ``--fake``.
  63. Alternatively, :class:`.SeparateDatabaseAndState` may be used to execute the
  64. backend-specific migrations and Django-generated migrations in a single
  65. operation.
  66. .. _cpk-and-relations:
  67. Composite primary keys and relations
  68. ====================================
  69. :ref:`Relationship fields <relationship-fields>`, including
  70. :ref:`generic relations <generic-relations>` do not support composite primary
  71. keys.
  72. For example, given the ``OrderLineItem`` model, the following is not
  73. supported::
  74. class Foo(models.Model):
  75. item = models.ForeignKey(OrderLineItem, on_delete=models.CASCADE)
  76. Because ``ForeignKey`` currently cannot reference models with composite primary
  77. keys.
  78. To work around this limitation, ``ForeignObject`` can be used as an
  79. alternative::
  80. class Foo(models.Model):
  81. item_order_id = models.IntegerField()
  82. item_product_id = models.CharField(max_length=20)
  83. item = models.ForeignObject(
  84. OrderLineItem,
  85. on_delete=models.CASCADE,
  86. from_fields=("item_order_id", "item_product_id"),
  87. to_fields=("order_id", "product_id"),
  88. )
  89. ``ForeignObject`` is much like ``ForeignKey``, except that it doesn't create
  90. any columns (e.g. ``item_id``), foreign key constraints or indexes in the
  91. database.
  92. .. warning::
  93. ``ForeignObject`` is an internal API. This means it is not covered by our
  94. :ref:`deprecation policy <internal-release-deprecation-policy>`.
  95. .. _cpk-and-database-functions:
  96. Composite primary keys and database functions
  97. =============================================
  98. Many database functions only accept a single expression.
  99. .. code-block:: sql
  100. MAX("order_id") -- OK
  101. MAX("product_id", "order_id") -- ERROR
  102. In these cases, providing a composite primary key reference raises a
  103. ``ValueError``, since it is composed of multiple column expressions. An
  104. exception is made for ``Count``.
  105. .. code-block:: python
  106. Max("order_id") # OK
  107. Max("pk") # ValueError
  108. Count("pk") # OK
  109. Composite primary keys in forms
  110. ===============================
  111. As a composite primary key is a virtual field, a field which doesn't represent
  112. a single database column, this field is excluded from ModelForms.
  113. For example, take the following form::
  114. class OrderLineItemForm(forms.ModelForm):
  115. class Meta:
  116. model = OrderLineItem
  117. fields = "__all__"
  118. This form does not have a form field ``pk`` for the composite primary key:
  119. .. code-block:: pycon
  120. >>> OrderLineItemForm()
  121. <OrderLineItemForm bound=False, valid=Unknown, fields=(product;order;quantity)>
  122. Setting the primary composite field ``pk`` as a form field raises an unknown
  123. field :exc:`.FieldError`.
  124. .. admonition:: Primary key fields are read only
  125. If you change the value of a primary key on an existing object and then
  126. save it, a new object will be created alongside the old one (see
  127. :attr:`.Field.primary_key`).
  128. This is also true of composite primary keys. Hence, you may want to set
  129. :attr:`.Field.editable` to ``False`` on all primary key fields to exclude
  130. them from ModelForms.
  131. Composite primary keys in model validation
  132. ==========================================
  133. Since ``pk`` is only a virtual field, including ``pk`` as a field name in the
  134. ``exclude`` argument of :meth:`.Model.clean_fields` has no effect. To exclude
  135. the composite primary key fields from
  136. :ref:`model validation <validating-objects>`, specify each field individually.
  137. :meth:`.Model.validate_unique` can still be called with ``exclude={"pk"}`` to
  138. skip uniqueness checks.
  139. Building composite primary key ready applications
  140. =================================================
  141. Prior to the introduction of composite primary keys, the single field composing
  142. the primary key of a model could be retrieved by introspecting the
  143. :attr:`primary key <django.db.models.Field.primary_key>` attribute of its
  144. fields:
  145. .. code-block:: pycon
  146. >>> pk_field = None
  147. >>> for field in Product._meta.get_fields():
  148. ... if field.primary_key:
  149. ... pk_field = field
  150. ... break
  151. ...
  152. >>> pk_field
  153. <django.db.models.fields.AutoField: id>
  154. Now that a primary key can be composed of multiple fields the
  155. :attr:`primary key <django.db.models.Field.primary_key>` attribute can no
  156. longer be relied upon to identify members of the primary key as it will be set
  157. to ``False`` to maintain the invariant that at most one field per model will
  158. have this attribute set to ``True``:
  159. .. code-block:: pycon
  160. >>> pk_fields = []
  161. >>> for field in OrderLineItem._meta.get_fields():
  162. ... if field.primary_key:
  163. ... pk_fields.append(field)
  164. ...
  165. >>> pk_fields
  166. []
  167. In order to build application code that properly handles composite primary
  168. keys the :attr:`_meta.pk_fields <django.db.models.options.Options.pk_fields>`
  169. attribute should be used instead:
  170. .. code-block:: pycon
  171. >>> Product._meta.pk_fields
  172. [<django.db.models.fields.AutoField: id>]
  173. >>> OrderLineItem._meta.pk_fields
  174. [
  175. <django.db.models.fields.ForeignKey: product>,
  176. <django.db.models.fields.ForeignKey: order>
  177. ]