< Django对象>不是JSON可序列化 [英] <Django object > is not JSON serializable

查看:123
本文介绍了< Django对象>不是JSON可序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码来序列化查询;

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

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

以下是我的 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 '值':{u'fr':[u'bar',u'r\xe9ception ouverte 24h / 24',u'chambres non-fumeurs',u'chambres familiales',........ 。]}] 

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

解决方案

simplejson json 不适用于django对象。



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

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

在您的情况下, self.get_queryset()包含django对象和dicts内部的混合。



一个选项是摆脱 self.get_queryset()中的模型实例,并使用 model_to_dict

  from django.forms.models import model_to_dict 

data = self.get_queryset( )

数据中的项目:
item ['product'] = model_to_dict(item ['product'])

return HttpResponse json.simplejson.dumps(data),mimetype =application / 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'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',.........]}]

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, mimetype="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.

这篇关于&lt; Django对象&gt;不是JSON可序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆