Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Fixed #18309 - Prefetch related does not work for fkey to multitable …

…inherited model

Thanks to milosu for the report, tests and initial patch.
  • Loading branch information...
commit 4fea46a030689d7ae774ee0217dbce28de5a1b29 1 parent f0664dc
@spookylukey spookylukey authored
View
4 django/db/models/fields/related.py
@@ -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:
View
3  tests/modeltests/prefetch_related/models.py
@@ -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
View
12 tests/modeltests/prefetch_related/tests.py
@@ -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):
@@ -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):
@@ -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):
Please sign in to comment.
Something went wrong with that request. Please try again.