我有以下用于序列化查询集的代码:
def render_to_response(self, context, **response_kwargs):
return HttpResponse(json.simplejson.dumps(list(self.get_queryset())),
mimetype="application/json")
以下是我的 get_quersety()
[{'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 对象和 dicts 组成。有任何想法吗?
原文由 tuna 发布,翻译遵循 CC BY-SA 4.0 许可协议
simplejson
和json
不能很好地处理 django 对象。Django 的内置 序列化 器只能序列化由 django 对象填充的查询集:
在您的情况下,
self.get_queryset()
内部包含 django 对象和 dicts 的混合。一种选择是删除
self.get_queryset()
中的模型实例,并使用model_to_dict
将它们替换为字典:希望有帮助。