以下内容为原创,转载请注明出处!

有时候我们在做评论和获取目录的时候,都会用到递归来查找所有的子数据,或者获取最上层的父数据,这时候都需要用到递归来获取,下面介绍drf怎么获取父子数据;


models.py

HT_TYPE = (
    (1, '图纸'),
    (2, '图标'),
    (3, '组件'),
    (4, '资源')
)
class HtMenu(models.Model):

    user_id = models.IntegerField(verbose_name='用户ID', help_text='用户ID')
    h_type = models.IntegerField(verbose_name='类型', help_text='类型;1:图纸,2:图标,3:组件,4:资源', choices=HT_TYPE ,default=1)
    name = models.CharField(max_length=64, verbose_name='名称', help_text='名称')
    parent = models.ForeignKey('self', verbose_name='父目录ID', help_text='父目录ID',
                               on_delete=models.CASCADE, related_name='child_menus', null=True, blank=True)

获取当前数据的所有子数据:

serializers.py

from rest_framework import serializers
from ht.models import HtMenu

__all__ = ['HtMenuSerializers']


class HtMenuSerializers(serializers.ModelSerializer):
    menus = serializers.SerializerMethodField()

    class Meta:
        model = HtMenu
        exclude = ('is_delete',)

    # 这里可实现递归查找所有的子元素
    def get_menus(self, obj):
        return HtMenuSerializers(obj.child_menus.all(), many=True).data

views.py

from rest_framework import viewsets
class HtMenuApi(viewsets.ViewSet):

    serializer_class = HtMenuSerializers
    # filter(parent_id=None)这里主要是获取的时候只获取最上层父元素,可根据具体需求来考虑是否过滤
    queryset = HtMenu.objects.filter(parent_id=None)

返回数据结果展示

[
    {
        "id": 1,
        "menus": [
            {
                "id": 2,
                "menus": [
                    {
                        "id": 3,
                        "menus": [],
                        "create_date": "2019-09-11 10:06:18",
                        "user_id": 1,
                        "h_type": 1,
                        "name": "热源监测",
                        "parent": 2
                    },
                    {
                        "id": 4,
                        "menus": [
                            {
                                "id": 6,
                                "menus": [],
                                "create_date": "2019-09-11 10:07:16",
                                "user_id": 1,
                                "h_type": 1,
                                "name": "水源2",
                                "parent": 4
                            }
                        ],
                        "create_date": "2019-09-11 10:06:54",
                        "user_id": 1,
                        "h_type": 1,
                        "name": "热源监测2",
                        "parent": 2
                    }
                ],
                "create_date": "2019-09-10 14:07:06",
                "user_id": 1,
                "h_type": 1,
                "name": "无人机",
                "parent": 1
            },
            {
                "id": 5,
                "menus": [],
                "create_date": "2019-09-11 10:07:10",
                "user_id": 1,
                "h_type": 1,
                "name": "水源",
                "parent": 1
            }
        ],
        "create_date": "2019-09-10 14:06:47",
        "user_id": 1,
        "h_type": 1,
        "name": "硬质合金冷镦模",
        "parent": null
    }
]


获取当前数据的父级数据:

serializers.py

from rest_framework import serializers
from ht.models import HtMenu

__all__ = ['HtMenuSerializers']


class HtMenuSerializers(serializers.ModelSerializer):
    parent = serializers.SerializerMethodField()
    
    class Meta:
        model = HtMenu
        exclude = ('is_delete',)

    def get_parent(self, obj):
        if obj.parent is not None:
            return HtMenuSerializers(obj.parent).data
        else:
            return None

views.py

from rest_framework import viewsets
class HtMenuApi(viewsets.ViewSet):

    serializer_class = HtMenuSerializers
    queryset = HtMenu.objects.all()

返回数据结果展示

{
    "id": 6,
    "parent": {
        "id": 4,
        "parent": {
            "id": 2,
            "parent": {
                "id": 1,
                "parent": null,
                "create_date": "2019-09-10 14:06:47",
                "user_id": 1,
                "h_type": 1,
                "name": "硬质合金冷镦模"
            },
            "create_date": "2019-09-10 14:07:06",
            "user_id": 1,
            "h_type": 1,
            "name": "无人机"
        },
        "create_date": "2019-09-11 10:06:54",
        "user_id": 1,
        "h_type": 1,
        "name": "热源监测2"
    },
    "create_date": "2019-09-11 10:07:16",
    "user_id": 1,
    "h_type": 1,
    "name": "水源2"
}