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

前端 未结 6 1254
独厮守ぢ
独厮守ぢ 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:06

    Objects cannot be stored in session from Django 1.6 or above. If you don't want to change the behavior of the cookie value(of a object), you can add a dictionary there. This can be used for non database objects like class object etc.

    from django.core.serializers.json import DjangoJSONEncoder
    import json     
    card_dict = card.__dict__
    card_dict .pop('_state', None) #Pop which are not json serialize
    card_dict = json.dumps(card_dict , cls=DjangoJSONEncoder)
    request.session['card'] = card_dict 
    

    Hope it will help you!

提交回复
热议问题