Skip to content

Commit 8488074

Browse files
charettessarahboyce
authored andcommitted
[5.1.x] Fixed #36197 -- Fixed improper many-to-many count() and exists() for non-pk to_field.
Regression in 66e47ac. Thanks mfontana-elem for the report and Sarah for the tests. Backport of c3a23aa from main.
1 parent a9d03c4 commit 8488074

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

django/db/models/fields/related_descriptors.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1219,7 +1219,7 @@ def constrained_target(self):
12191219
return None
12201220
hints = {"instance": self.instance}
12211221
manager = self.through._base_manager.db_manager(db, hints=hints)
1222-
filters = {self.source_field_name: self.instance.pk}
1222+
filters = {self.source_field_name: self.related_val[0]}
12231223
# Nullable target rows must be excluded as well as they would have
12241224
# been filtered out from an INNER JOIN.
12251225
if self.target_field.null:

docs/releases/5.1.7.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,8 @@ Bugfixes
1616
* Fixed a bug in Django 5.1 where ``FileSystemStorage``, with
1717
``allow_overwrite`` set to ``True``, did not truncate the overwritten file
1818
content (:ticket:`36191`).
19+
20+
* Fixed a regression in Django 5.1 where the ``count`` and ``exists`` methods
21+
of ``ManyToManyField`` related managers would always return ``0`` and
22+
``False`` when the intermediary model back references used ``to_field``
23+
(:ticket:`36197`).

tests/m2m_through/tests.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -533,3 +533,11 @@ def test_choices(self):
533533
[choice[0] for choice in field.get_choices(include_blank=False)],
534534
["pea", "potato", "tomato"],
535535
)
536+
537+
def test_count(self):
538+
self.assertEqual(self.curry.ingredients.count(), 3)
539+
self.assertEqual(self.tomato.recipes.count(), 1)
540+
541+
def test_exists(self):
542+
self.assertTrue(self.curry.ingredients.exists())
543+
self.assertTrue(self.tomato.recipes.exists())

0 commit comments

Comments
 (0)