Skip to content

Commit

Permalink
Fixed #7530, #7716 -- When using select_related() and encountering a …
Browse files Browse the repository at this point in the history
…NULL

related object, populate the attribute correctly. Patch from Bastien Kleineidam.


git-svn-id: http://code.djangoproject.com/svn/django/trunk@8098 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information
malcolmt committed Jul 27, 2008
1 parent aee55ce commit f488551
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 10 deletions.
6 changes: 5 additions & 1 deletion django/db/models/query.py
Expand Up @@ -785,7 +785,11 @@ def get_cached_row(klass, row, index_start, max_depth=0, cur_depth=0,

restricted = requested is not None
index_end = index_start + len(klass._meta.fields)
obj = klass(*row[index_start:index_end])
fields = row[index_start:index_end]
if not [x for x in fields if x is not None]:
# If we only have a list of Nones, there was not related object.
return None, index_end
obj = klass(*fields)
for f in klass._meta.fields:
if not select_related_descend(f, restricted, requested):
continue
Expand Down
18 changes: 9 additions & 9 deletions tests/regressiontests/null_fk/models.py
@@ -1,8 +1,5 @@
"""
Regression tests for proper working of ForeignKey(null=True). Tests these bugs:
* #7369: FK non-null after null relationship on select_related() generates an invalid query
Regression tests for proper working of ForeignKey(null=True).
"""

from django.db import models
Expand Down Expand Up @@ -38,7 +35,8 @@ def __unicode__(self):
# Starting from comment, make sure that a .select_related(...) with a specified
# set of fields will properly LEFT JOIN multiple levels of NULLs (and the things
# that come after the NULLs, or else data that should exist won't).
# that come after the NULLs, or else data that should exist won't). Regression
# test for #7369.
>>> c = Comment.objects.select_related().get(id=1)
>>> c.post
<Post: First Post>
Expand All @@ -47,9 +45,11 @@ def __unicode__(self):
None
>>> comments = Comment.objects.select_related('post__forum__system_info').all()
>>> [(c.id, c.post.id) for c in comments]
[(1, 1), (2, None)]
>>> [(c.comment_text, c.post.title) for c in comments]
[(u'My first comment', u'First Post'), (u'My second comment', None)]
>>> [(c.id, c.comment_text, c.post) for c in comments]
[(1, u'My first comment', <Post: First Post>), (2, u'My second comment', None)]
# Regression test for #7530, #7716.
>>> Comment.objects.select_related('post').filter(post__isnull=True)[0].post is None
True
"""}

0 comments on commit f488551

Please sign in to comment.