Skip to content

Commit

Permalink
Fixed #18309 - Prefetch related does not work for fkey to multitable …
Browse files Browse the repository at this point in the history
…inherited model

Thanks to milosu for the report, tests and initial patch.
  • Loading branch information
spookylukey committed Jun 6, 2012
1 parent f0664dc commit 4fea46a
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
4 changes: 2 additions & 2 deletions django/db/models/fields/related.py
Expand Up @@ -329,10 +329,10 @@ def get_query_set(self, **db_hints):
return QuerySet(self.field.rel.to).using(db)

def get_prefetch_query_set(self, instances):
rel_obj_attr = attrgetter(self.field.rel.field_name)
other_field = self.field.rel.get_related_field()
rel_obj_attr = attrgetter(other_field.attname)
instance_attr = attrgetter(self.field.attname)
instances_dict = dict((instance_attr(inst), inst) for inst in instances)
other_field = self.field.rel.get_related_field()
if other_field.rel:
params = {'%s__pk__in' % self.field.rel.field_name: instances_dict.keys()}
else:
Expand Down
3 changes: 3 additions & 0 deletions tests/modeltests/prefetch_related/models.py
Expand Up @@ -68,6 +68,9 @@ def __unicode__(self):
class Meta:
ordering = ['id']

class BookReview(models.Model):
book = models.ForeignKey(BookWithYear)
notes = models.TextField(null=True, blank=True)

## Models for default manager tests

Expand Down
12 changes: 11 additions & 1 deletion tests/modeltests/prefetch_related/tests.py
Expand Up @@ -7,7 +7,7 @@

from .models import (Author, Book, Reader, Qualification, Teacher, Department,
TaggedItem, Bookmark, AuthorAddress, FavoriteAuthors, AuthorWithAge,
BookWithYear, Person, House, Room, Employee, Comment)
BookWithYear, BookReview, Person, House, Room, Employee, Comment)


class PrefetchRelatedTests(TestCase):
Expand Down Expand Up @@ -335,6 +335,10 @@ def setUp(self):
self.authorAddress = AuthorAddress.objects.create(
author=self.author1, address='SomeStreet 1')
self.book2.aged_authors.add(self.author2, self.author3)
self.br1 = BookReview.objects.create(
book=self.book1, notes="review book1")
self.br2 = BookReview.objects.create(
book=self.book2, notes="review book2")

def test_foreignkey(self):
with self.assertNumQueries(2):
Expand All @@ -343,6 +347,12 @@ def test_foreignkey(self):
for obj in qs]
self.assertEqual(addresses, [[unicode(self.authorAddress)], [], []])

def test_foreignkey_to_inherited(self):
with self.assertNumQueries(2):
qs = BookReview.objects.prefetch_related('book')
titles = [obj.book.title for obj in qs]
self.assertEquals(titles, ["Poems", "More poems"])

def test_m2m_to_inheriting_model(self):
qs = AuthorWithAge.objects.prefetch_related('books_with_year')
with self.assertNumQueries(2):
Expand Down

0 comments on commit 4fea46a

Please sign in to comment.