Ticket #36109: filteredrelation_stack.diff

File filteredrelation_stack.diff, 2.1 KB (added by Peter DeVita, 8 hours ago)
  • django/db/models/sql/query.py

    diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py
    index 293856d86f..96660edd2f 100644
    a b class Query(BaseExpression):  
    19221922            reuse = can_reuse if join.m2m else None
    19231923            alias = self.join(connection, reuse=reuse)
    19241924            joins.append(alias)
     1925            if join.filtered_relation and can_reuse is not None:
     1926                can_reuse.add(alias)
    19251927        return JoinInfo(final_field, targets, opts, joins, path, final_transformer)
    19261928
    19271929    def trim_joins(self, targets, joins, path):
  • tests/filtered_relation/tests.py

    diff --git a/tests/filtered_relation/tests.py b/tests/filtered_relation/tests.py
    index 82caba8662..f0d68db9d7 100644
    a b class FilteredRelationTests(TestCase):  
    582582            lambda x: (x.author, x.book_title, x.preferred_by_author_pk),
    583583        )
    584584
     585    def test_three_level_nested_chained_relations(self):
     586        borrower1 = Borrower.objects.create(name="Jenny")
     587        # borrower 1 reserves, rents, and returns book1.
     588        Reservation.objects.create(
     589            borrower=borrower1,
     590            book=self.book1,
     591            state=Reservation.STOPPED,
     592        )
     593        qs = (
     594            Author.objects.annotate(
     595                my_books=FilteredRelation(
     596                    "book"
     597                ),
     598                my_reserved_books=FilteredRelation(
     599                    "my_books__reservation",
     600                    condition=Q(my_books__reservation__state=Reservation.STOPPED)
     601                ),
     602                my_readers=FilteredRelation(
     603                    "my_reserved_books__borrower",
     604                    condition=Q(my_reserved_books__borrower=borrower1)
     605                )
     606            )
     607        )
     608
     609        qs = qs.filter(
     610            my_readers=borrower1
     611        )
     612        self.assertQuerySetEqual(
     613            qs,
     614            [
     615                ("Alice",)
     616            ],
     617            lambda x: (x.name,),
     618        )
     619
     620
    585621    def test_deep_nested_foreign_key(self):
    586622        qs = (
    587623            Book.objects.annotate(
Back to Top