TypeError对象id不是JSON可序列化的

时间:2017-04-26 13:02:43

标签: json django url serialization django-templates

我有一个Django视图,当模板尝试渲染时会引发错误:

  

TypeError:不是JSON可序列化的

(其中76是id字段) 这是视图

def view2(request, model1object_id):
    model1object = Model1.objects.get(pk=model1object_id)

    # HERE

    session_object = request.session.get('content')
    if session_object:
        del request.session['content']
    request.session['content'] = model1object


    context = {
        "model1object": model1object,
        ....
    }    
    return render(request, 'app/template2.html', context)

这是Model1的模型:

class Model1(models.Model):
    date_field = models.DateField()
    another_field = models.CharField(max_length= 50, default="...")

    def __str__(self):
        return unicode(self.id) or u''

    def get_absolute_url(self):
        return reverse('app:model1', kwargs={'id': self.id})

编辑:追溯 - >

Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 235, in get_response
    response = middleware_method(request, response)
  File "/Library/Python/2.7/site-packages/django/contrib/sessions/middleware.py", line 50, in process_response
    request.session.save()
  File "/Library/Python/2.7/site-packages/django/contrib/sessions/backends/db.py", line 82, in save
    obj = self.create_model_instance(data)
  File "/Library/Python/2.7/site-packages/django/contrib/sessions/backends/db.py", line 68, in create_model_instance
    session_data=self.encode(data),
  File "/Library/Python/2.7/site-packages/django/contrib/sessions/backends/base.py", line 91, in encode
    serialized = self.serializer().dumps(session_dict)
  File "/Library/Python/2.7/site-packages/django/core/signing.py", line 95, in dumps
    return json.dumps(obj, separators=(',', ':')).encode('latin-1')
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 250, in dumps
    sort_keys=sort_keys, **kw).encode(obj)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <Model1: 76> is not JSON serializable

感谢

1 个答案:

答案 0 :(得分:2)

错误是因为您尝试在会话中保存模型实例,并且会话中间件无法将其序列化为JSON。

request.session['content'] = model1object

存储对象的id而不是对象本身就足够了。

request.session['content_id'] = model1object.id 
...
# retrieve from db later
model1object = Model1.objects.get(id=request.session['content_id'])

如果您需要在会话中存储比id更多的信息,那么您必须将其转换为JSON可序列化的格式。对于一个简单的模型,最简单的方法是创建一个Python字典。

request.session['content'] = {
    'id': model1object.id,
    'name': model1object.name,
    ...
}

对于更复杂的模型,您可以查看serializing Django objects上的文档。