我有以下代码用于序列化查询集:
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 组成。有什么想法吗?
最佳答案
simplejson
和 json
不适用于 django 对象。
Django 的内置 serializers只能序列化用 django 对象填充的查询集:
data = serializers.serialize('json', self.get_queryset())
return HttpResponse(data, content_type="application/json")
在您的情况下, self.get_queryset()
包含 django 对象和内部字典的混合。
一种选择是删除 self.get_queryset()
中的模型实例,并使用 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")
希望对您有所帮助。
关于python - <Django 对象> 不是 JSON 可序列化的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16790375/
相关文章:
python - 如何在 Django 中不使用模板返回 JSON?
javascript - 如何通过 Ajax 请求将 Select2 与 JSON 一起使用?
javascript - 如何将 JSON 转换为 CSV 格式并存储在变量中
json - Postgres : How to convert a json string to
ios - 在 Swift 中将 JSON 字符串转换为 Object 的简单而干净的方法
python - 如何以不同的顺序比较具有相同元素的两个 JSON 对象相等?