Skip to content

Instantly share code, notes, and snippets.

@pyshawon
Forked from bsnux/gist:4672788
Created July 15, 2020 18:18
Show Gist options
  • Select an option

  • Save pyshawon/4f39c6b32bbd17be72ee3632affe99df to your computer and use it in GitHub Desktop.

Select an option

Save pyshawon/4f39c6b32bbd17be72ee3632affe99df 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment