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):
|
1922 | 1922 | reuse = can_reuse if join.m2m else None |
1923 | 1923 | alias = self.join(connection, reuse=reuse) |
1924 | 1924 | joins.append(alias) |
| 1925 | if join.filtered_relation and can_reuse is not None: |
| 1926 | can_reuse.add(alias) |
1925 | 1927 | return JoinInfo(final_field, targets, opts, joins, path, final_transformer) |
1926 | 1928 | |
1927 | 1929 | def trim_joins(self, targets, joins, path): |
diff --git a/tests/filtered_relation/tests.py b/tests/filtered_relation/tests.py
index 82caba8662..f0d68db9d7 100644
a
|
b
|
class FilteredRelationTests(TestCase):
|
582 | 582 | lambda x: (x.author, x.book_title, x.preferred_by_author_pk), |
583 | 583 | ) |
584 | 584 | |
| 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 | |
585 | 621 | def test_deep_nested_foreign_key(self): |
586 | 622 | qs = ( |
587 | 623 | Book.objects.annotate( |