以所需格式序列化Django对象

时间:2018-09-25 09:14:54

标签: python django python-3.x extjs django-models

我有一个存储模型,其中使用序列化获取对象:

tree_data = serializers.serialize ("json", Storage.objects.all ())

它看起来像这样:

[
  {"model": "hello_extjs.storage", "pk": 9, "fields": {"code": "000", "name": "Title 1", "id_parent": 0}},
  {"model": "hello_extjs.storage", "pk": 10, "fields": {"code": "111", "name": "Test 1", "id_parent": 9}},
  {"model": "hello_extjs.storage", "pk": 11, "fields": {"code": "222", "name": "Test 2", "id_parent": 9}},
  {"model": "hello_extjs.storage", "pk": 12, "fields": {"code": "333", "name": "Title 2", "id_parent": 0}},
  {"model": "hello_extjs.storage", "pk": 13, "fields": {"code": "444", "name": "Test 3", "id_parent": 12}},
  {"model": "hello_extjs.storage", "pk": 14, "fields": {"code": "555", "name": "Test 4", "id_parent": 12}}

]

我需要使用以下形式的数据:

{
    text: 'Storage',
    expanded: true,
    children: [{
        text: "Title 1",
        children: [{
            text: "Test 1",
            leaf: true
        }, {
            text: "Test 2",
            leaf: true
        }],
        leaf: false,
        "expanded": true
    }, {
        text: "Title 2",
        children: [{
            text: "Test 3",
            leaf: true
        }, {
            text: "Test 4",
            leaf: true
        }],
        leaf: false,
        "expanded": true
    }]
}

我应该如何序列化对象以获取所需形式的数据?

1 个答案:

答案 0 :(得分:0)

Django的内置序列化器旨在满足Django的需求-将整个查询集转储到Fixture并重新加载该Fixture,显然,它不会生成您想要的非常特定的格式。因此,解决方案很简单:首先从模型中编写自定义代码,以将期望的结构生成为Python字典(仅包含字典,列表,字符串,布尔值和数字-兼容json的小数),然后将其传递给json.dumps()。问题解决了。

最终,您可能希望查看类似serpy的内容,以帮助您使用自定义序列化代码...