From 8be0c0d6901669661fca578f474cd51cd284d35a Mon Sep 17 00:00:00 2001 From: Simon Charette Date: Thu, 8 May 2025 14:02:35 -0400 Subject: Fixed #36373 -- Fixed select_related() crash on foreign object for a composite pk. Thanks Jacob Walls for the report and Sarah for the in-depth review. --- django/db/models/query.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'django') diff --git a/django/db/models/query.py b/django/db/models/query.py index 4ba96928d4..663f8bade4 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -2678,7 +2678,11 @@ class RelatedPopulator: ) self.model_cls = klass_info["model"] - self.pk_idx = self.init_list.index(self.model_cls._meta.pk.attname) + # A primary key must have all of its constituents not-NULL as + # NULL != NULL and thus NULL cannot be referenced through a foreign + # relationship. Therefore checking for a single member of the primary + # key is enough to determine if the referenced object exists or not. + self.pk_idx = self.init_list.index(self.model_cls._meta.pk_fields[0].attname) self.related_populators = get_related_populators(klass_info, select, self.db) self.local_setter = klass_info["local_setter"] self.remote_setter = klass_info["remote_setter"] -- cgit v1.3