Opened 12 years ago

Closed 12 years ago

Last modified 10 years ago

#18849 closed Uncategorized (needsinfo)

Add caching to SingleObjectMixin.get_object()

Reported by: anonymous Owned by: nobody
Component: Generic views Version: 1.4
Severity: Normal Keywords:
Cc: m.r.sopacua@… Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: yes Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description

Repeated calls to get_object() fetch the same object from the database. The object should only be fetched once and cached for subsequent calls.

Currently you have to pass the object around to various methods within your view (for example if you are using an attribute in get_success_url) to avoid calling get_object() multiple times if you are not using it in a view that sets self.object.

Change History (2)

comment:1 by Melvyn Sopacua, 12 years ago

Cc: m.r.sopacua@… added
Needs tests: set
Resolution: needsinfo
Status: newclosed

First of all queries are cached and only re-fetched if a query is made that alters data. Secondly, class-based views start life as either get() or post() and those two methods are responsible for setting self.object. This is the object SingleObjectMixin should be working with. If self.object is set to None then no object should be created, because there is insufficient data: CreateView.get() is the prime example.
If you feel too many queries are made, please provide accurate data and preferably a test case that shows the problem.

comment:2 by Joachim Jablon, 10 years ago

Just to add a bit of detail :

If you want to override the get or post (or dispatch) method of a CBV, and you need to do a specific operation after self.object is set and before super() is called, then you can't use super(), which can mess up a lot of mixin uses.

If get_object was cached, then you could do

self.object = self.get_object()

youself, and you'd know that when the base class does its own self.get_object(), it would not make a new SQL query.

I had several cases where I had to make my own CacheObjectMixin with adds caching to self.object, but I think there could be a easier way.

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