radious
radious

Reputation: 830

Django - cache queryset for object_list

I'm using an object_list() method manually in one of my views for pagination and some other cool autmation stuff. I try to cache huge queryset and take care of everything what can influence object_list (eg. request.GET['page']) but simpled idea looks like:

def some_view(request):
qs = cache.get('key')
if qs == None:
    qs = QS.objects.filter(some_huge_query)
    cache.set('key', qs)
return object_list(queryset = qs,...)

Actually queryset is executed once again during template rendering. Is there any way to prevent queryset from being executed?

Upvotes: 0

Views: 2259

Answers (4)

Botond Béres
Botond Béres

Reputation: 16683

As far as I know:

if qs == None:

might evaluate your queryset. At least I'm pretty sure that if qs or if not qs evaluates the queryset.

Try:

if qs is not None:

Also it would be useful to see your object_list method and template.

Upvotes: 0

Bernhard Vallant
Bernhard Vallant

Reputation: 50806

You need to store the evaluated queryset in your cache, so you should call:

cache.set('key', list(qs))

to force the queryset be evaluated to a list; otherwise it will be merely the query being stored in the cache!

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239460

The line:

if qs = None:

is the problem. You're storing None in qs instead of checking equality (==). As a result, qs is always None, and gets r-evaluated each time through.

You need to change it to:

if qs == None:

Or, just simply:

if not qs:

Upvotes: 2

Brandon Taylor
Brandon Taylor

Reputation: 34593

You could use a values_list to turn that huge QuerySet into a list and then hand that list to the template, which should cause the QuerySet to be re-evaluated.

Upvotes: 0

Related Questions