Opened 7 years ago

Closed 7 years ago

Last modified 7 years ago

#18435 closed Cleanup/optimization (invalid)

Caching of reverse ForeignKey lookups

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


Currently ForeignKey ( lookups ( are cached. Does it make sense to cache reverse ForeignKey lookups as well? Currently the following results in two queries:

author.book_set.all()[0] # db query
author.book_set.all()[0] # another db query

Change History (3)

comment:1 Changed 7 years ago by Aymeric Augustin

Resolution: invalid
Status: newclosed

There's a misunderstanding somewhere; your example isn't related to #14270.

This will do two requests:


and so will this:


and so will this:


This is the expected behavior, really. (And we can't change it easily, since people are relying on this to reload objects whose state may have changed from the database).

comment:2 Changed 7 years ago by Selwin Ong

Sorry you're right, it's not related to #14270. I just find it odd that forward ForeignKey lookups are cached for performance reasons, but not the other way round (and both of them are db related operations).

So this produces one query:

While this produces two queries:


I know that it probably has always been like this in django, but is this something that can be fixed down the road?

comment:3 Changed 7 years ago by Aymeric Augustin

Ah, yes, now I get your point. Indeed, you aren't building a entirely new graph of objects (unlike my first example). But you're still building a new queryset.

And that's why caching "multiple related objects" is much harder than caching "single related objects". author.book_set is actually a QuerySet, on which you can apply an arbitrary number of further operations. Caching would have to take this into account.

Since this is a new feature, and a complicated one, I suggest you bring it up on the django-developers mailing list for discussion (if possible with a proof-of-concept implementation).

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