Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: saving a query set to session

I am trying to save query result obtained in one view to session, and retrieve it in another view, so I tried something like below:

def default (request):
    equipment_list = Equipment.objects.all()

    request.session['export_querset'] = equipment_list

However, this gives me

TypeError at /calbase/

<QuerySet [<Equipment: A>, <Equipment: B>, <Equipment: C>]> is not JSON serializable

I am wondering what does this mean exactly and how should I go about it? Or maybe there is alternative way of doing what I want besides using session?

like image 639
Hansong Li Avatar asked Dec 11 '22 15:12

Hansong Li


1 Answers

If this is what you are saving:

 equipment_list = Equipment.objects.all()

You shouldn't or wouldn't need to use sessions. Why? Because this is a simple query without any filtering. equipment_list would be common to all the users. This can quite easily be saved in the cache

 from django.core.cache import cache

 equipment_list = cache.get('equipment_list')
 if not equipment_list:
     equipment_list = Equipment.objects.all()
     cache.set('equipment_list',equipment_list)

Note that a queryset can be saved in the cache without it having to be converted to values first.

Update:
One of the other answers mention that a querysets are not json serializable. That's only applicable when you are trying to pass that off as a json response. Isn't applicable when you are trying to cache it because django.core.cache does not use json serialization it uses pickling.

like image 118
e4c5 Avatar answered Dec 28 '22 10:12

e4c5