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

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

    --> DON'T EVER FEEL LIKE DOING SOMETHING LIKE THIS! <--
    Django using session and ctypes: Plz read Martijn Pieters explanation comment below.

    class MyObject:
      def stuff(self):
        return "stuff..."
    
    my_obj = MyObject()
    request.session['id_my_obj'] = id(my_obj)
    
    ...
    
    id_my_obj = request.session.get('id_my_obj')
    
    import ctypes
    obj = ctypes.cast(id_my_obj, ctypes.py_object).value
    
    print(obj.stuff())    
    # returns "stuff..."
    

提交回复
热议问题