summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSimon Charette <charette.s@gmail.com>2025-02-17 13:45:31 -0500
committerSarah Boyce <42296566+sarahboyce@users.noreply.github.com>2025-02-18 11:45:45 +0100
commit8488074fe38edbea6c4ec822c59c7c45d0669a91 (patch)
treedf6ad6370254fe5d4b84b80acfd6c6cf1a5ef35e
parenta9d03c409406f3f95f692bc5545ebacc7f4e2e4f (diff)
[5.1.x] Fixed #36197 -- Fixed improper many-to-many count() and exists() for non-pk to_field.
Regression in 66e47ac69a7e71cf32eee312d05668d8f1ba24bb. Thanks mfontana-elem for the report and Sarah for the tests. Backport of c3a23aa02faa1cf1d32e43d66858e793cd9ecac4 from main.
-rw-r--r--django/db/models/fields/related_descriptors.py2
-rw-r--r--docs/releases/5.1.7.txt5
-rw-r--r--tests/m2m_through/tests.py8
3 files changed, 14 insertions, 1 deletions
diff --git a/django/db/models/fields/related_descriptors.py b/django/db/models/fields/related_descriptors.py
index bc288c47ec..6541df1b7c 100644
--- a/django/db/models/fields/related_descriptors.py
+++ b/django/db/models/fields/related_descriptors.py
@@ -1219,7 +1219,7 @@ def create_forward_many_to_many_manager(superclass, rel, reverse):
return None
hints = {"instance": self.instance}
manager = self.through._base_manager.db_manager(db, hints=hints)
- filters = {self.source_field_name: self.instance.pk}
+ filters = {self.source_field_name: self.related_val[0]}
# Nullable target rows must be excluded as well as they would have
# been filtered out from an INNER JOIN.
if self.target_field.null:
diff --git a/docs/releases/5.1.7.txt b/docs/releases/5.1.7.txt
index deda4f2f92..c32f8f5ae1 100644
--- a/docs/releases/5.1.7.txt
+++ b/docs/releases/5.1.7.txt
@@ -16,3 +16,8 @@ Bugfixes
* Fixed a bug in Django 5.1 where ``FileSystemStorage``, with
``allow_overwrite`` set to ``True``, did not truncate the overwritten file
content (:ticket:`36191`).
+
+* Fixed a regression in Django 5.1 where the ``count`` and ``exists`` methods
+ of ``ManyToManyField`` related managers would always return ``0`` and
+ ``False`` when the intermediary model back references used ``to_field``
+ (:ticket:`36197`).
diff --git a/tests/m2m_through/tests.py b/tests/m2m_through/tests.py
index 83449a7c7b..81a47a2083 100644
--- a/tests/m2m_through/tests.py
+++ b/tests/m2m_through/tests.py
@@ -533,3 +533,11 @@ class M2mThroughToFieldsTests(TestCase):
[choice[0] for choice in field.get_choices(include_blank=False)],
["pea", "potato", "tomato"],
)
+
+ def test_count(self):
+ self.assertEqual(self.curry.ingredients.count(), 3)
+ self.assertEqual(self.tomato.recipes.count(), 1)
+
+ def test_exists(self):
+ self.assertTrue(self.curry.ingredients.exists())
+ self.assertTrue(self.tomato.recipes.exists())