Opened 2 hours ago

#36617 new Bug

RelatedManager QuerySet with filters on the same relation do not add inner joins

Reported by: Florian Dahms Owned by:
Component: Database layer (models, ORM) Version: 5.2
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

When using the QuerySet from a RelatedManager I cannot do subsequent filters over the same relation.

Given I have these models:

class A(models.Model):
    x = models.IntegerField()
    pass


class B(models.Model):
    foo = models.ManyToManyField(A, related_name='bars')

then I would expect the following tests to pass:

class ExampleTestCase(TestCase):
    def setUp(self):
        A.objects.create(x=1)
        A.objects.create(x=2)
        b = B.objects.create()
        b.foo.set(A.objects.all())

    def test_1(self):
        self.assertEqual(B.objects.filter(foo__x=1).filter(foo__x=2).count(),
                         1)

    def test_2(self):
        self.assertEqual(A.objects.get(x=1).bars.filter(foo__x=2).count(),
                         1)

The QuerySet from B.objects.filter(foo__x=1) behaves different than the one from A.objects.get(x=1).bars (I would expect them to behave in the same way). In test_1, the SQL has two INNER JOINs and in test_2 it is only one.

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top