小编典典

<Django对象>不可JSON序列化

django

我有以下用于序列化查询集的代码;

def render_to_response(self, context, **response_kwargs):

    return HttpResponse(json.simplejson.dumps(list(self.get_queryset())),
                        mimetype="application/json")

以下是我的 get_querset()

[{'product': <Product: hederello ()>, u'_id': u'9802', u'_source': {u'code': u'23981', u'facilities': [{u'facility': {u'name': {u'fr': u'G\xe9n\xe9ral', u'en': u'General'}, u'value': {u'fr': [u'bar', u'r\xe9ception ouverte 24h/24', u'chambres non-fumeurs', u'chambres familiales',.........]}]

我需要序列化。但是它说不能序列化<Product: hederello ()>。因为列表由Django对象和字典组成。有任何想法吗 ?


阅读 637

收藏
2020-03-27

共1个答案

小编典典

simplejson并且json不能很好地与Django对象配合使用。

Django的内置序列化器只能序列化由django对象填充的查询集:

data = serializers.serialize('json', self.get_queryset())
return HttpResponse(data, content_type="application/json")

在你的情况下,self.get_queryset()其中包含django对象和dict的混合。

一种选择是摆脱中的模型实例,self.get_queryset()并使用dict将其替换为model_to_dict

from django.forms.models import model_to_dict

data = self.get_queryset()

for item in data:
   item['product'] = model_to_dict(item['product'])

return HttpResponse(json.simplejson.dumps(data), mimetype="application/json")

希望能有所帮助。

2020-03-27