#22757: prefetch_related isn't as effecient as it could be with 
GenericForeignKey
and proxy models
--------------------------------------+--------------------
     Reporter:  gwahl@…               |      Owner:  nobody
         Type:  Uncategorized         |     Status:  new
    Component:  contrib.contenttypes  |    Version:  1.6
     Severity:  Normal                |   Keywords:
 Triage Stage:  Unreviewed            |  Has patch:  0
Easy pickings:  0                     |      UI/UX:  0
--------------------------------------+--------------------
 `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)`

-- 
Ticket URL: <https://code.djangoproject.com/ticket/22757>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-updates+unsubscr...@googlegroups.com.
To post to this group, send email to django-updates@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/062.7f6b36f8a2de48e0ea40115847479ff0%40djangoproject.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to