diff --git a/django/db/models/query.py b/django/db/models/query.py index 7492039b2c4..f301753e122 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -1203,7 +1203,7 @@ def get_cached_row(klass, row, index_start, max_depth=0, cur_depth=0, # If the base object exists, populate the # descriptor cache setattr(obj, f.get_cache_name(), rel_obj) - if f.unique: + if f.unique and rel_obj is not None: # If the field is unique, populate the # reverse descriptor cache on the related object setattr(rel_obj, f.related.get_cache_name(), obj) diff --git a/tests/regressiontests/select_related_onetoone/models.py b/tests/regressiontests/select_related_onetoone/models.py index 00142787681..6b46366530c 100644 --- a/tests/regressiontests/select_related_onetoone/models.py +++ b/tests/regressiontests/select_related_onetoone/models.py @@ -44,3 +44,12 @@ class StatDetails(models.Model): class AdvancedUserStat(UserStat): pass + + +class Image(models.Model): + name = models.CharField(max_length=100) + + +class Product(models.Model): + name = models.CharField(max_length=100) + image = models.OneToOneField(Image, null=True) diff --git a/tests/regressiontests/select_related_onetoone/tests.py b/tests/regressiontests/select_related_onetoone/tests.py index b9e5beb7e9f..5a4a3e4ed69 100644 --- a/tests/regressiontests/select_related_onetoone/tests.py +++ b/tests/regressiontests/select_related_onetoone/tests.py @@ -2,7 +2,8 @@ from django import db from django.conf import settings from django.test import TestCase -from models import User, UserProfile, UserStat, UserStatResult, StatDetails, AdvancedUserStat +from models import (User, UserProfile, UserStat, UserStatResult, StatDetails, + AdvancedUserStat, Image, Product) class ReverseSelectRelatedTestCase(TestCase): def setUp(self): @@ -81,3 +82,10 @@ class ReverseSelectRelatedTestCase(TestCase): stat = UserStat.objects.select_related('advanceduserstat').get(posts=200) self.assertEqual(stat.advanceduserstat.posts, 200) self.assertQueries(1) + + def test_nullable_relation(self): + im = Image.objects.create(name="imag1") + p1 = Product.objects.create(name="Django Plushie", image=im) + p2 = Product.objects.create(name="Talking Django Plushie") + + self.assertEqual(len(Product.objects.select_related("image")), 2)