Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #17541 -- Fixed non-saved/nullable fk querying

  • Loading branch information...
commit 55da775ce1bfba20db33b56c29957faa63917980 1 parent 34ee7d9
Anssi Kääriäinen authored January 06, 2013
2  django/db/models/fields/related.py
@@ -496,6 +496,8 @@ def get_query_set(self):
6  tests/regressiontests/many_to_one_regress/models.py
@@ -48,3 +48,9 @@ class Relation(models.Model):
48 48
 
49 49
     def __str__(self):
50 50
         return "%s - %s" % (self.left.category.name, self.right.category.name)
  51
+
  52
+class Car(models.Model):
  53
+    make = models.CharField(max_length=100, null=True, unique=True)
  54
+
  55
+class Driver(models.Model):
  56
+    car = models.ForeignKey(Car, to_field='make', null=True, related_name='drivers')
25  tests/regressiontests/many_to_one_regress/tests.py
@@ -4,7 +4,8 @@
4 4
 from django.test import TestCase
5 5
 from django.utils import six
6 6
 
7  
-from .models import First, Third, Parent, Child, Category, Record, Relation
  7
+from .models import (
  8
+    First, Third, Parent, Child, Category, Record, Relation, Car, Driver)
8 9
 
9 10
 
10 11
 class ManyToOneRegressionTests(TestCase):
@@ -111,3 +112,25 @@ def test_fk_instantiation_outside_model(self):
111 112
         # of a model, and interrogate its related field.
112 113
         cat = models.ForeignKey(Category)
113 114
         self.assertEqual('id', cat.rel.get_related_field().name)
  115
+
  116
+    def test_relation_unsaved(self):
  117
+        # Test that the <field>_set manager does not join on Null value fields (#17541)
  118
+        Third.objects.create(name='Third 1')
  119
+        Third.objects.create(name='Third 2')
  120
+        th = Third(name="testing")
  121
+        # The object isn't saved an thus the relation field is null - we won't even
  122
+        # execute a query in this case.
  123
+        with self.assertNumQueries(0):
  124
+            self.assertEqual(th.child_set.count(), 0)
  125
+        th.save()
  126
+        # Now the model is saved, so we will need to execute an query.
  127
+        with self.assertNumQueries(1):
  128
+            self.assertEqual(th.child_set.count(), 0)
  129
+    
  130
+    def test_related_null_to_field(self):
  131
+        c1 = Car.objects.create()
  132
+        c2 = Car.objects.create()
  133
+        d1 = Driver.objects.create()
  134
+        self.assertIs(d1.car, None)
  135
+        with self.assertNumQueries(0):
  136
+            self.assertEqual(list(c1.drivers.all()), [])

0 notes on commit 55da775

Please sign in to comment.
Something went wrong with that request. Please try again.