composite-primary-key.txt 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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 creating a model set the ``pk`` field to
  11. 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 a composite primary key. This sets the associated
  31. 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. Composite primary keys and database functions
  96. =============================================
  97. Many database functions only accept a single expression.
  98. .. code-block:: sql
  99. MAX("order_id") -- OK
  100. MAX("product_id", "order_id") -- ERROR
  101. As a consequence, they cannot be used with composite primary key references as
  102. they are composed of multiple column expressions.
  103. .. code-block:: python
  104. Max("order_id") # OK
  105. Max("pk") # ERROR
  106. Composite primary keys in forms
  107. ===============================
  108. As a composite primary key is a virtual field, a field which doesn't represent
  109. a single database column, this field is excluded from ModelForms.
  110. For example, take the following form::
  111. class OrderLineItemForm(forms.ModelForm):
  112. class Meta:
  113. model = OrderLineItem
  114. fields = "__all__"
  115. This form does not have a form field ``pk`` for the composite primary key:
  116. .. code-block:: pycon
  117. >>> OrderLineItemForm()
  118. <OrderLineItemForm bound=False, valid=Unknown, fields=(product;order;quantity)>
  119. Setting the primary composite field ``pk`` as a form field raises an unknown
  120. field :exc:`.FieldError`.
  121. .. admonition:: Primary key fields are read only
  122. If you change the value of a primary key on an existing object and then
  123. save it, a new object will be created alongside the old one (see
  124. :attr:`.Field.primary_key`).
  125. This is also true of composite primary keys. Hence, you may want to set
  126. :attr:`.Field.editable` to ``False`` on all primary key fields to exclude
  127. them from ModelForms.