Opened 14 years ago

Closed 9 years ago

#15844 closed Bug (fixed)

Filtering by related objects causes unnecessary extra db hits when using model inheritance

Reported by: Johannes Dollinger Owned by: nobody
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The failing test below illustrates the issue.

from django.test import TestCase
from django.db import models

class A(models.Model): pass
class B(A): pass

class R(models.Model):
     b = models.ForeignKey(B, related_name="r")


class T(TestCase):
     def test(self):
        b = B.objects.create()
        r = R.objects.create(b=b)
        # Fails: produces 2 queries
        self.assertNumQueries(1, lambda: list(R.objects.filter(b=b)))
        # Fails: produces 2 queries
        self.assertNumQueries(1, lambda: list(b.r.all())


The extra queries seem to be generated by RelatedField._pk_trace().

Attachments (1)

15844.r16622.diff (5.4 KB ) - added by Johannes Dollinger 13 years ago.

Download all attachments as: .zip

Change History (7)

comment:1 by Carl Meyer, 14 years ago

Easy pickings: unset
Triage Stage: UnreviewedAccepted

by Johannes Dollinger, 13 years ago

Attachment: 15844.r16622.diff added

comment:2 by Johannes Dollinger, 13 years ago

Has patch: set
UI/UX: unset

comment:3 by Preston Holmes, 13 years ago

Patch needs improvement: set

Why were code comments deleted in patch? They still seem valid, otherwise they should be updated not deleted.

comment:4 by Tim Graham, 9 years ago

Patch needs improvement: unset

Looks like this was fixed in Django 1.6 with 97774429aeb54df4c09895c07cd1b09e70201f7d.

PR to add a regression test.

comment:5 by Tim Graham <timograham@…>, 9 years ago

In fa2e1e63:

Refs #15844 -- Added tests for multi-table inheritance related object filtering efficiency.

Fixed in 97774429aeb54df4c09895c07cd1b09e70201f7d.

comment:6 by Tim Graham, 9 years ago

Resolution: fixed
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top