Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store django objects as session variables ( object is not JSON serializable)?

Tags:

python

django

I have a simple view

def foo(request):
   card = Card.objects.latest(datetime)
   request.session['card']=card

For the above code I get the error

"<Card: Card object> is not JSON serializable"

Django version 1.6.2. What am I doing wrong ?

like image 681
Akash Deshpande Avatar asked Mar 10 '14 07:03

Akash Deshpande


People also ask

How does Django store objects in session?

There are two simple ways to do this. If each object belongs to a single session at the same time, store session id as a model field, and update models. If an object can belong to multiple sessions at the same time, store object.id as a session variable.


2 Answers

There are two simple ways to do this.

  • If each object belongs to a single session at the same time, store session id as a model field, and update models.
  • If an object can belong to multiple sessions at the same time, store object.id as a session variable.
like image 24
kdani Avatar answered Sep 24 '22 06:09

kdani


In a session, I'd just store the object primary key:

request.session['card'] = card.id

and when loading the card from the session, obtain the card again with:

try:
    card = Card.objects.get(id=request.session['card'])
except (KeyError, Card.DoesNotExist):
    card = None

which will set card to None if there isn't a card entry in the session or the specific card doesn't exist.

By default, session data is serialised to JSON. You could also provide your own serializer, which knows how to store the card.id value or some other representation and, on deserialization, produce your Card instance again.

like image 184
Martijn Pieters Avatar answered Sep 21 '22 06:09

Martijn Pieters