summaryrefslogtreecommitdiff
path: root/docs/topics
diff options
context:
space:
mode:
authorSimon Charette <charette.s@gmail.com>2025-01-12 23:06:46 -0500
committerSarah Boyce <42296566+sarahboyce@users.noreply.github.com>2025-01-14 16:20:17 +0100
commite580926d74f4d5788feac05ac1d50626936631d7 (patch)
tree580c60c380128f6c2b69eaf5526f8c2447039a96 /docs/topics
parentf2a1dcaa53626ff11b921ef142b780a8fd746d32 (diff)
Fixed #36075 -- Documented how to introspect composite primary keys.
Document _meta.pk_fields and interactions between Field.primary_key and CompositePrimaryKey. Thanks Mariusz for the review.
Diffstat (limited to 'docs/topics')
-rw-r--r--docs/topics/composite-primary-key.txt49
1 files changed, 49 insertions, 0 deletions
diff --git a/docs/topics/composite-primary-key.txt b/docs/topics/composite-primary-key.txt
index f252f318c1..b43df68dfc 100644
--- a/docs/topics/composite-primary-key.txt
+++ b/docs/topics/composite-primary-key.txt
@@ -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>
+ ]