Python <Django 对象> 不是 JSON 可序列化的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16790375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:42:09  来源:igfitidea点击:

<Django object > is not JSON serializable

pythondjangojsonserializationdjango-class-based-views

提问by tuna

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()

以下是我的 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 ?

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

采纳答案by alecxe

simplejsonand jsondon't work with django objects well.

simplejson并且json不能很好地处理 django 对象。

Django's built-in serializerscan only serialize querysets filled with django objects:

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

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.

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

One option is to get rid of model instances in the self.get_queryset()and replace them with dicts using model_to_dict:

一种选择是摆脱模型实例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")

Hope that helps.

希望有帮助。

回答by tuna

First I added a to_dict method to my model ;

首先,我在模型中添加了一个 to_dict 方法;

def to_dict(self):
    return {"name": self.woo, "title": self.foo}

Then I have this;

然后我有这个;

class DjangoJSONEncoder(JSONEncoder):

    def default(self, obj):
        if isinstance(obj, models.Model):
            return obj.to_dict()
        return JSONEncoder.default(self, obj)


dumps = curry(dumps, cls=DjangoJSONEncoder)

and at last use this class to serialize my queryset.

最后使用这个类来序列化我的查询集。

def render_to_response(self, context, **response_kwargs):
    return HttpResponse(dumps(self.get_queryset()))

This works quite well

这很好用

回答by Danny Staple

I found that this can be done rather simple using the ".values" method, which also gives named fields:

我发现这可以使用“.values”方法来完成,该方法还提供命名字段:

result_list = list(my_queryset.values('first_named_field', 'second_named_field'))
return HttpResponse(json.dumps(result_list))

"list" must be used to get data as iterable, since the "value queryset" type is only a dict if picked up as an iterable.

“列表”必须用于获取可迭代的数据,因为“值查询集”类型只是作为可迭代的字典。

Documentation: https://docs.djangoproject.com/en/1.7/ref/models/querysets/#values

文档:https: //docs.djangoproject.com/en/1.7/ref/models/querysets/#values

回答by Yash

From version 1.9 Easier and official way of getting json

从版本 1.9 获取 json 的更简单和官方的方式

from django.http import JsonResponse
from django.forms.models import model_to_dict


return JsonResponse(  model_to_dict(modelinstance) )

回答by YPCrumble

The easiest way is to use a JsonResponse.

最简单的方法是使用JsonResponse

For a queryset, you should pass a list of the the valuesfor that queryset, like so:

对于查询集,您应该传递该查询集的列表values,如下所示:

from django.http import JsonResponse

queryset = YourModel.objects.filter(some__filter="some value").values()
return JsonResponse({"models_to_return": list(queryset)})

回答by Woody Johnson

Our js-programmer asked me to return the exact JSON format data instead of a json-encoded string to her.

我们的 js 程序员让我向她返回确切的 JSON 格式数据而不是 json 编码的字符串。

Below is the solution.(This will return an object that can be used/viewed straightly in the browser)

下面是解决方案。(这将返回一个可以在浏览器中直接使用/查看的对象)

import json
from xxx.models import alert
from django.core import serializers

def test(request):
    alert_list = alert.objects.all()

    tmpJson = serializers.serialize("json",alert_list)
    tmpObj = json.loads(tmpJson)

    return HttpResponse(json.dumps(tmpObj))