#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 |
Description
Currently ForeignKey (https://docs.djangoproject.com/en/dev/topics/db/queries/#one-to-many-relationships) lookups (https://code.djangoproject.com/ticket/14270) 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 by , 13 years ago
Resolution: | → invalid |
---|---|
Status: | new → closed |
comment:2 by , 13 years ago
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:
book.author book.author
While this produces two queries:
author.book_set.all() author.book_set.all()
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 by , 13 years ago
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).
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).