home / django_tickets / tickets

tickets: 22757

This data as json

id created changetime last_pulled_from_trac stage status component type severity version resolution summary description owner reporter keywords easy has_patch needs_better_patch needs_tests needs_docs ui_ux
22757 2014-06-03 23:00:26 2017-07-10 21:58:11 2022-03-06 04:20:15.263455 Accepted assigned Database layer (models, ORM) Cleanup/optimization Normal dev   prefetch_related isn't as effecient as it could be with GenericForeignKey and proxy models `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)` czpython gwahl@fusionbox.com prefetch_related 0 0 0 0 0 0
Powered by Datasette · Queries took 0.849ms