﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
22757	prefetch_related isn't as effecient as it could be with GenericForeignKey and proxy models	gwahl@…		"`prefetch_related` is able to prefetch across a GenericForiegnKey. However, it does more queries than necessary when using proxy models.

Our models:

{{{#!python
from django.db import models
from django.contrib.contenttypes.generic import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class Parent(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    child = GenericForeignKey('content_type', 'object_id', for_concrete_model=False)

class Child(models.Model):
    pass

class ProxiedChild(Child):
    class Meta:
        proxy = True
}}}

Now create some instances

{{{
>>> child = Child.objects.create()
>>> proxied_child = ProxiedChild.objects.create()
>>> p1 = Parent.objects.create(child=child)
>>> p2 = Parent.objects.create(child=proxied_child)
}}}

And query using prefetch_related: 

{{{
>>> Parent.objects.all().prefetch_related('child')
SELECT ""foo_parent"".""id"", ""foo_parent"".""content_type_id"", ""foo_parent"".""object_id"" FROM ""foo_parent"" LIMIT 21

SELECT ""foo_child"".""id"" FROM ""foo_child"" WHERE ""foo_child"".""id"" IN (3)

SELECT ""foo_child"".""id"" FROM ""foo_child"" WHERE ""foo_child"".""id"" IN (2)
}}}

This is doing 3 queries instead of the expected 2. The two queries for the `foo_child` table should be combined to be `""foo_child"".""id"" IN (2, 3)`"	Cleanup/optimization	new	Database layer (models, ORM)	dev	Normal		prefetch_related	Simon Charette	Accepted	0	0	0	0	0	0
