Code

Ticket #17541: 17541-3.diff

File 17541-3.diff, 2.1 KB (added by nate_b, 2 years ago)
Line 
1From 9026e16e30802d831b86d353164966fb5d648eff Mon Sep 17 00:00:00 2001
2From: Nate Bragg <jonathan.bragg@alum.rpi.edu>
3Date: Tue, 17 Jan 2012 06:47:31 -0500
4Subject: [PATCH] My attempt at 17541
5
6---
7 django/db/models/fields/related.py                 |    5 ++++-
8 tests/regressiontests/many_to_one_regress/tests.py |    7 +++++++
9 2 files changed, 11 insertions(+), 1 deletions(-)
10
11diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
12index 848fd6e..f369666 100644
13--- a/django/db/models/fields/related.py
14+++ b/django/db/models/fields/related.py
15@@ -458,7 +458,10 @@ class ForeignRelatedObjectsDescriptor(object):
16                     return self.instance._prefetched_objects_cache[rel_field.related_query_name()]
17                 except (AttributeError, KeyError):
18                     db = self._db or router.db_for_read(self.model, instance=self.instance)
19-                    return super(RelatedManager, self).get_query_set().using(db).filter(**self.core_filters)
20+                    r = super(RelatedManager, self).get_query_set().using(db).filter(**self.core_filters)
21+                    if getattr(self.instance, attname) is None:
22+                        return r.none()
23+                    return r
24 
25             def get_prefetch_query_set(self, instances):
26                 db = self._db or router.db_for_read(self.model)
27diff --git a/tests/regressiontests/many_to_one_regress/tests.py b/tests/regressiontests/many_to_one_regress/tests.py
28index 9e04fb4..8c91723 100644
29--- a/tests/regressiontests/many_to_one_regress/tests.py
30+++ b/tests/regressiontests/many_to_one_regress/tests.py
31@@ -106,3 +106,10 @@ class ManyToOneRegressionTests(TestCase):
32         # of a model, and interrogate its related field.
33         cat = models.ForeignKey(Category)
34         self.assertEqual('id', cat.rel.get_related_field().name)
35+
36+    def test_related_relation_on_none(self):
37+        # Test that the <field>_set manager does not join on Null value fields (#17541)
38+        Third.objects.create(name='Third 1')
39+        Third.objects.create(name='Third 2')
40+        th = Third(name="testing")
41+        self.assertEqual(th.child_set.count(), 0)
42--
431.7.5.4
44