简体   繁体   English

使用 Django REST 框架序列化 Django-mptt 模型

[英]Django-mptt model serialize with Django REST framework

I have used django-mptt to store categories hierarchy and I need to serialize all category data in below format.我使用 django-mptt 来存储类别层次结构,我需要以以下格式序列化所有类别数据。

{
            "id": 1,
            "name": "FOOD"
            "children": [
                {
                    "id": 6,
                    "name": "PIZZA"
                },
                {
                    "id": 7,
                    "name": "BURGER"
                }
            ],

        },
        {
            "id": 2,
            "name": "ALCOHOL"
            "children": [
                {
                    "id": 8,
                    "name": "WINE"
                },
                {
                    "id": 9,
                    "name": "VODKA"
                }
            ],

        },
}

I'm using django REST framework ModelViewset and serializers.我正在使用 django REST 框架 ModelViewset 和序列化程序。 How to do so?怎么做?

This response is a year too late, but for the benefit of others, use RecursiveField from the djangorestframework-recursive package , which can be installed via:这反应了一年为时已晚,但对于其他人的利益,使用RecursiveFielddjangorestframework递归的包,它可以通过安装:

pip3 install djangorestframework-recursive

I was able to do it like so:我能够这样做:

from rest_framework_recursive.fields import RecursiveField

class MyModelRecursiveSerializer(serializers.Serializer):
    # your other fields

    children = serializers.ListField(
        read_only=True, source='your_get_children_method', child=RecursiveField()
    ) 

Just be aware that this is potentially expensive, so you might want to only use this for models whose entries do not change that often and cache the results.请注意,这可能很昂贵,因此您可能只想将其用于条目不经常更改并缓存结果的模型。

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

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