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