Created
January 30, 2013 11:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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...
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
Thank you. This is exactly what I needed and couldn't find for ages.