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

前端 未结 6 1359
独厮守ぢ
独厮守ぢ 2021-02-13 17:58

I have a simple view

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

For the above code I get the

6条回答
  •  半阙折子戏
    2021-02-13 18:23

    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.

提交回复
热议问题