lt;Django object gt; is not JSON serializable(lt;Django 对象gt;不是 JSON 可序列化的)
问题描述
I have the following code for serializing the queryset;
def render_to_response(self, context, **response_kwargs):
return HttpResponse(json.simplejson.dumps(list(self.get_queryset())),
mimetype="application/json")
And following is my get_querset()
[{'product': <Product: hederello ()>, u'_id': u'9802', u'_source': {u'code': u'23981', u'facilities': [{u'facility': {u'name': {u'fr': u'Gxe9nxe9ral', u'en': u'General'}, u'value': {u'fr': [u'bar', u'rxe9ception ouverte 24h/24', u'chambres non-fumeurs', u'chambres familiales',.........]}]
Which I need to serialize. But it says not able to serialize the <Product: hederello ()>
. Because list composed of both django objects and dicts. Any ideas ?
simplejson
and json
don't work with django objects well.
Django's built-in serializers can only serialize querysets filled with django objects:
data = serializers.serialize('json', self.get_queryset())
return HttpResponse(data, content_type="application/json")
In your case, self.get_queryset()
contains a mix of django objects and dicts inside.
One option is to get rid of model instances in the self.get_queryset()
and replace them with dicts using 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")
Hope that helps.
这篇关于<Django 对象>不是 JSON 可序列化的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:<Django 对象>不是 JSON 可序列化的
基础教程推荐
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01