Skip to content

Instantly share code, notes, and snippets.

@bsnux
Created January 30, 2013 11:49
Show Gist options
  • Save bsnux/4672788 to your computer and use it in GitHub Desktop.
Save bsnux/4672788 to your computer and use it in GitHub Desktop.
Storing Django queryset in session. Useful when you need to pass querysets between requests
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)
@kstratis
Copy link

Thank you. This is exactly what I needed and couldn't find for ages.

@matm
Copy link

matm commented Dec 4, 2014

Thanks for sharing. Serializing just the query (that get pickled) in the database is a great idea. Most other implementations save the whole queryset in the session data...

@grwhumphries
Copy link

Clever bit of code - thanks for sharing this - streamlines things a lot for me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment