Code

Ticket #12819: django-select-related.diff

File django-select-related.diff, 2.4 KB (added by Alex, 4 years ago)
Line 
1diff --git a/django/db/models/query.py b/django/db/models/query.py
2index 7492039..f301753 100644
3--- a/django/db/models/query.py
4+++ b/django/db/models/query.py
5@@ -1203,7 +1203,7 @@ def get_cached_row(klass, row, index_start, max_depth=0, cur_depth=0,
6                 # If the base object exists, populate the
7                 # descriptor cache
8                 setattr(obj, f.get_cache_name(), rel_obj)
9-            if f.unique:
10+            if f.unique and rel_obj is not None:
11                 # If the field is unique, populate the
12                 # reverse descriptor cache on the related object
13                 setattr(rel_obj, f.related.get_cache_name(), obj)
14diff --git a/tests/regressiontests/select_related_onetoone/models.py b/tests/regressiontests/select_related_onetoone/models.py
15index 0014278..6b46366 100644
16--- a/tests/regressiontests/select_related_onetoone/models.py
17+++ b/tests/regressiontests/select_related_onetoone/models.py
18@@ -44,3 +44,12 @@ class StatDetails(models.Model):
19 
20 class AdvancedUserStat(UserStat):
21     pass
22+
23+
24+class Image(models.Model):
25+    name = models.CharField(max_length=100)
26+
27+
28+class Product(models.Model):
29+    name = models.CharField(max_length=100)
30+    image = models.OneToOneField(Image, null=True)
31diff --git a/tests/regressiontests/select_related_onetoone/tests.py b/tests/regressiontests/select_related_onetoone/tests.py
32index b9e5beb..5a4a3e4 100644
33--- a/tests/regressiontests/select_related_onetoone/tests.py
34+++ b/tests/regressiontests/select_related_onetoone/tests.py
35@@ -2,7 +2,8 @@ from django import db
36 from django.conf import settings
37 from django.test import TestCase
38 
39-from models import User, UserProfile, UserStat, UserStatResult, StatDetails, AdvancedUserStat
40+from models import (User, UserProfile, UserStat, UserStatResult, StatDetails,
41+    AdvancedUserStat, Image, Product)
42 
43 class ReverseSelectRelatedTestCase(TestCase):
44     def setUp(self):
45@@ -81,3 +82,10 @@ class ReverseSelectRelatedTestCase(TestCase):
46         stat = UserStat.objects.select_related('advanceduserstat').get(posts=200)
47         self.assertEqual(stat.advanceduserstat.posts, 200)
48         self.assertQueries(1)
49+   
50+    def test_nullable_relation(self):
51+        im = Image.objects.create(name="imag1")
52+        p1 = Product.objects.create(name="Django Plushie", image=im)
53+        p2 = Product.objects.create(name="Talking Django Plushie")
54+       
55+        self.assertEqual(len(Product.objects.select_related("image")), 2)