-
-
Notifications
You must be signed in to change notification settings - Fork 33.1k
Fixed #36075 -- Documented how to introspect composite primary keys. #19036
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -185,3 +185,52 @@ field :exc:`.FieldError`. | |
This is also true of composite primary keys. Hence, you may want to set | ||
:attr:`.Field.editable` to ``False`` on all primary key fields to exclude | ||
them from ModelForms. | ||
|
||
Building composite primary key ready applications | ||
================================================= | ||
|
||
Prior to the introduction of composite primary keys, the single field composing | ||
the primary key of a model could be retrieved by introspecting the | ||
:attr:`primary key <django.db.models.Field.primary_key>` attribute of its | ||
fields: | ||
|
||
.. code-block:: pycon | ||
|
||
>>> pk_field = None | ||
>>> for field in Product._meta.get_fields(): | ||
... if field.primary_key: | ||
... pk_field = field | ||
... break | ||
... | ||
>>> pk_field | ||
<django.db.models.fields.AutoField: id> | ||
|
||
Now that a primary key can be composed of multiple fields the | ||
:attr:`primary key <django.db.models.Field.primary_key>` attribute can no | ||
longer be relied upon to identify members of the primary key as it will be set | ||
to ``False`` to maintain the invariant that at most one field per model will | ||
|
||
have this attribute set to ``True``: | ||
|
||
.. code-block:: pycon | ||
|
||
>>> pk_fields = [] | ||
>>> for field in OrderLineItem._meta.get_fields(): | ||
... if field.primary_key: | ||
... pk_fields.append(field) | ||
... | ||
>>> pk_fields | ||
[] | ||
|
||
In order to build application code that properly handles composite primary | ||
keys the :attr:`_meta.pk_fields <django.db.models.options.Options.pk_fields>` | ||
|
||
attribute should be used instead: | ||
|
||
.. code-block:: pycon | ||
|
||
>>> Product._meta.pk_fields | ||
[<django.db.models.fields.AutoField: id>] | ||
>>> OrderLineItem._meta.pk_fields | ||
[ | ||
<django.db.models.fields.ForeignKey: product>, | ||
<django.db.models.fields.ForeignKey: order> | ||
] |
Uh oh!
There was an error while loading. Please reload this page.