# Join reuse on reverse fk chained queries

**URL:** <https://forum.djangoproject.com/t/join-reuse-on-reverse-fk-chained-queries/24328>\
**Category:** Using the ORM\
**Created:** [October 5, 2023, 4:16pm UTC](https://forum.djangoproject.com/t/join-reuse-on-reverse-fk-chained-queries/24328 "2023-10-05T16:16:04Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![renatoalencar](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/renatoalencar/32/16278_2.png) [@renatoalencar](https://forum.djangoproject.com/u/renatoalencar)\
**Post date:** [October 5, 2023, 4:16pm UTC](https://forum.djangoproject.com/t/join-reuse-on-reverse-fk-chained-queries/24328/1 "2023-10-05T16:16:04Z")

</div>

When recently debugging a query, I noticed that when doing a query on a lookup for a reverse many to one relationship the join isn’t reused, which causes a double JOIN on the final SQL causing repeated results.

Example using the Book/Author example:

```auto
Author.objects.filter(book __title='Example', book__ year=2020) # Only a single reused JOIN
# Returns a different result than
Author.objects.filter(Book__title='Example').filter(book__year=2020) # Two joins generated on the final SQL query

```

Moreover appending a `.count()` to the end of the query will result on a different outcome, for a single author/book pair, the first one will return 1 and the second 2.

While investigating the issue, I’ve noticed there’s actually a test case covering that here: [https://github.com/django/django/blob/main/tests/queries/tests.py#L3858](https://github.com/django/django/blob/main/tests/queries/tests.py#L3858)

Why is it like that? Should chained filters like that behave just like adding them together?

---

<div class="post-metadata">

**Author:** ![charettes](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/charettes/32/27_2.png) [@charettes](https://forum.djangoproject.com/u/charettes)\
**Post date:** [October 5, 2023, 4:46pm UTC](https://forum.djangoproject.com/t/join-reuse-on-reverse-fk-chained-queries/24328/2 "2023-10-05T16:46:38Z")

</div>

👋 @renatoalencar

This is explained in details in the [Spanning multi-valued relationships section](https://docs.djangoproject.com/en/4.2/topics/db/queries/#spanning-multi-valued-relationships) of the documentation and is a common source of confusion but can’t be changed for obvious backward compatibility reasons.

If you want to reuse a join across `filter` calls your best bet is likely to use [a `FilteredRelation` annotation](https://docs.djangoproject.com/en/4.2/ref/models/querysets/#filteredrelation-objects) instead.
