Question

In Django 1.6 I've got a model stored in my database which I am querying in order to get a number of results back. However since the results may sometimes be more than enough to fill a page, I am trying to implement the pagination system narrowly following the skeleton of this post: https://stackoverflow.com/a/18106904/178728.

Now the problem that in request.session I need to store my queryset and not just plain values. However this creates all sorts of problems as Django complains that my queryset is not json serializable.

So far I've tried doing:

1) request.session['data'] = myQueryset # Fails
2) request.session['data'] = serializers.serialize('json', myQueryset) 
   # succeeds at first but fails in deserialization as
   # I can't reassemble the original queryset 

Anyway my question is this: What's the easiest way to store and then retrieve my queryset?

Note that I need to store the queryset when a user searches the db using a POST request and then retrieve the results through GET for use within the paginator.

Thanks in advance.

Was it helpful?

Solution

I just found a solution to my problem: This is exactly what I was looking for: https://gist.github.com/bsnux/4672788

import pickle

# Session key
key = 'my_qs'

# Pizza => model example
qs = Pizza.objects.filter(ingredient='tomato')
# Dumping data
request.session[key] = pickle.dumps(qs.query)

# Loading data
pizzas = Pizza.objects.all()[:1]
pizzas.query = pickle.loads(request.session[key])

# Using qs
for pizza in pizzas:
print(pizza.ingredient)

Hopefully this helps someone in the future. Cheers.

OTHER TIPS

Try

myQueryset.values()

It should return JSON-seralizable queryset.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top