diff --git a/django/db/models/fields/related_descriptors.py b/django/db/models/fields/related_descriptors.py index 6e9f7bccbf7..e61ee077f09 100644 --- a/django/db/models/fields/related_descriptors.py +++ b/django/db/models/fields/related_descriptors.py @@ -647,15 +647,6 @@ def create_reverse_many_to_one_manager(superclass, rel): self.core_filters = {self.field.name: instance} - # Even if this relation is not to pk, we require still pk value. - # The wish is that the instance has been already saved to DB, - # although having a pk value isn't a guarantee of that. - if self.instance.pk is None: - raise ValueError( - f"{instance.__class__.__name__!r} instance needs to have a primary " - f"key value before this relationship can be used." - ) - def __call__(self, *, manager): manager = getattr(self.model, manager) manager_class = create_reverse_many_to_one_manager(manager.__class__, rel) @@ -720,6 +711,14 @@ def create_reverse_many_to_one_manager(superclass, rel): pass # nothing to clear from cache def get_queryset(self): + # Even if this relation is not to pk, we require still pk value. + # The wish is that the instance has been already saved to DB, + # although having a pk value isn't a guarantee of that. + if self.instance.pk is None: + raise ValueError( + f"{self.instance.__class__.__name__!r} instance needs to have a " + f"primary key value before this relationship can be used." + ) try: return self.instance._prefetched_objects_cache[ self.field.remote_field.get_cache_name() diff --git a/docs/releases/4.1.1.txt b/docs/releases/4.1.1.txt index 3c218274f21..f97015b9fa0 100644 --- a/docs/releases/4.1.1.txt +++ b/docs/releases/4.1.1.txt @@ -49,3 +49,6 @@ Bugfixes * Fixed a regression in Django 4.1 that caused an incorrect migration when renaming a model with ``ManyToManyField`` and ``db_table`` (:ticket:`33953`). + +* Reallowed, following a regression in Django 4.1, creating reverse foreign key + managers on unsaved instances (:ticket:`33952`). diff --git a/tests/many_to_one/tests.py b/tests/many_to_one/tests.py index d9a8984c4c0..ae9bce6b44c 100644 --- a/tests/many_to_one/tests.py +++ b/tests/many_to_one/tests.py @@ -758,6 +758,9 @@ class ManyToOneTests(TestCase): ) with self.assertRaisesMessage(ValueError, msg): th.child_set.count() + # The reverse foreign key manager can be created. + self.assertEqual(th.child_set.model, Third) + th.save() # Now the model is saved, so we will need to execute a query. with self.assertNumQueries(1):