简体   繁体   English

django:控制json序列化

[英]django: control json serialization

Is there a way to control json serialization in django? 有没有办法控制django中的json序列化? Simple code below will return serialized object in json: 下面的简单代码将返回json中的序列化对象:

co = Collection.objects.all()
c = serializers.serialize('json',co)

The json will look similar to this: json看起来与此类似:

[
    {
        "pk": 1,
        "model": "picviewer.collection",
        "fields": {
            "urlName": "architecture",
            "name": "\u0413\u043e\u0440\u043e\u0434 \u0438 \u0430\u0440\u0445\u0438\u0442\u0435\u043a\u0442\u0443\u0440\u0430",
            "sortOrder": 0
        }
    },
    {
        "pk": 2,
        "model": "picviewer.collection",
        "fields": {
            "urlName": "nature",
            "name": "\u041f\u0440\u0438\u0440\u043e\u0434\u0430",
            "sortOrder": 1
        }
    },
    {
        "pk": 3,
        "model": "picviewer.collection",
        "fields": {
            "urlName": "objects",
            "name": "\u041e\u0431\u044a\u0435\u043a\u0442\u044b \u0438 \u043d\u0430\u0442\u044e\u0440\u043c\u043e\u0440\u0442",
            "sortOrder": 2
        }
    }
]

You can see it's serializing it in a way that you are able to re-create the whole model, shall you want to do this at some point - fair enough, but not very handy for simple JS ajax in my case: I want bring the traffic to minimum and make the whole thing little clearer. 您可以看到它以一种能够重新创建整个模型的方式对其进行序列化,您是否希望在某些时候执行此操作 - 公平,但在我的情况下对于简单的JS ajax不是很方便:我想带来交通最小化,使整个事情变得更加清晰。

What I did is I created a view that passes the object to a .json template and the template will do something like this to generate "nicer" json output: 我做的是创建了一个视图,将对象传递给.json模板,模板将执行类似这样的操作以生成“更好”的json输出:

[
{% if collections %}
    {% for c in collections %}
{"id": {{c.id}},"sortOrder": {{c.sortOrder}},"name": "{{c.name}}","urlName": "{{c.urlName}}"}{% if not forloop.last %},{% endif %}
    {% endfor %}
{% endif %}
]

This does work and the output is much (?) nicer: 这确实有效,输出更好(?)更好:

[
    {
        "id": 1,
        "sortOrder": 0,
        "name": "Город и архитектура",
        "urlName": "architecture"
    },
    {
        "id": 2,
        "sortOrder": 1,
        "name": "Природа",
        "urlName": "nature"
    },
    {
        "id": 3,
        "sortOrder": 2,
        "name": "Объекты и натюрморт",
        "urlName": "objects"
    } 
]

However, I'm bothered by the fast that my solution uses templates (an extra step in processing and possible performance impact) and it will take manual work to maintain shall I update the model, for example. 但是,我对我的解决方案使用模板的快速(处理中的额外步骤和可能的性能影响)感到困扰,并且需要手动工作来维护,例如,我应该更新模型。

I'm thinking json generating should be part of the model (correct me if I'm wrong) and done with either native python-json and django implementation but can't figure how to make it strip the bits that I don't want. 我认为json生成应该是模型的一部分(如果我错了,请纠正我)并使用本机python-json和django实现,但无法弄清楚如何使它剥离我不想要的位。

One more thing - even when I restrict it to a set of fields to serialize, it will keep the id always outside the element container and instead present it as "pk" outside of it. 还有一件事 - 即使我将它限制为一组要序列化的字段,它也会使id始终位于元素容器之外,而是将其作为“pk”存在于其外部。

I would suggest you use the json library to encode your data, instead of just constructing the json-like string yourself. 我建议你使用json库来编码你的数据,而不是自己构建类似json的字符串。 The code above doesn't seem to handle escaping properly, for one thing. 一方面,上面的代码似乎没有正确处理转义。 And there's not much to gain by writing your own serializer (except for bugs). 编写自己的序列化程序(bug除外)并没有多大好处。

That's really easy. 这真的很容易。 Quick example: 快速举例:

from django.http import HttpResponse
from django.utils import simplejson

def simple_view(request):
    response = {'string': "test",
                'number': 42,
                'array': [1, 2, 3],
                'js_object': dict(foo="bar")}
    return HttpResponse(simplejson.dumps(response),
                        mimetype="application/json")

This view will return the equivalent of the following JSON: 该视图将返回以下JSON的等效内容:

{"string": "test",
 "number": 42,
 "array": [1, 2, 3],
 "js_object": {foo: "bar"}}

EDIT: And yes, Assaf Lavie is right, your template can spew invalid JSON. 编辑:是的,Assaf Lavie是对的,你的模板可以喷出无效的JSON。

def view( request):
    m_all = list(model.objects.all().values())

    return HttpResponse(simplejson.dumps(m_all))

This should solve the problem. 这应该可以解决问题。 Using values() and converting to list should produce the result you wanted. 使用值()并转换为列表应该产生您想要的结果。

Rather than writing anything yourself, let Piston do the work of serializing Django models to JSON. Piston将Django模型序列化为JSON,而不是自己编写任何东西。 By default it just serializes the model's fields, no metadata. 默认情况下,它只是序列化模型的字段,没有元数据。 And you can easily list which fields--even related fields--to include or exclude. 您可以轻松列出要包含或排除的字段(甚至是相关字段)。 No extra templates, and very little view code. 没有额外的模板,也没有很少的视图代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM