Opened 4 years ago

Closed 17 hours ago

#15844 closed Bug (fixed)

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

Reported by: emulbreh Owned by: nobody
Component: Database layer (models, ORM) Version: master
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


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 emulbreh 4 years ago.

Download all attachments as: .zip

Change History (7)

comment:1 Changed 4 years ago by carljm

  • Easy pickings unset
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Triage Stage changed from Unreviewed to Accepted

Changed 4 years ago by emulbreh

comment:2 Changed 4 years ago by emulbreh

  • Has patch set
  • UI/UX unset

comment:3 Changed 4 years ago by ptone

  • Patch needs improvement set

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

comment:4 Changed 30 hours ago by timgraham

  • Patch needs improvement unset

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

PR to add a regression test.

comment:5 Changed 17 hours ago by Tim Graham <timograham@…>

In fa2e1e63:

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

Fixed in 97774429aeb54df4c09895c07cd1b09e70201f7d.

comment:6 Changed 17 hours ago by timgraham

  • Resolution set to fixed
  • Status changed from new to closed
Note: See TracTickets for help on using tickets.
Back to Top