From 65b451ae3e3017154e352d300ae6f8152c506b06 Mon Sep 17 00:00:00 2001 From: Joseph Kocherhans Date: Tue, 23 Feb 2010 19:24:27 +0000 Subject: [PATCH] Fixed #12819. Fixed a bug with caching values of nullable 1to1 fields. Thanks, s.angel@twidi.com for the initial patch, and Alex Gaynor for the tests. git-svn-id: http://code.djangoproject.com/svn/django/trunk@12543 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/db/models/query.py | 2 +- .../regressiontests/select_related_onetoone/models.py | 9 +++++++++ tests/regressiontests/select_related_onetoone/tests.py | 10 +++++++++- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/django/db/models/query.py b/django/db/models/query.py index 7492039b2c..f301753e12 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 0014278768..6b46366530 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 b9e5beb7e9..5a4a3e4ed6 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)