多级评论接口数据的处理方法

多级评论,采用列表嵌套字典,循环字典,自关联字段,循环添加,根据内存地址一致保持数据一致性

from api import models
from rest_framework import serializers


class ListCommentSerializer(serializers.ModelSerializer):
    create_datetime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
    children = serializers.SerializerMethodField()

    class Meta:
        model = models.Comment
        fields = ['create_datetime', 'reply', 'content', 'children']

    def get_children(self, obj):
        # 获取当前根评论的所有的子孙评论(后台)
        descendant_queryset = models.Comment.objects.filter(root=obj).order_by('id')
        descendant_dict = {}
        """
        {
            11:{"reply":2,children:[],"content":"oooadfa","depth":1,"create_datetime":"2021-09-0122:32:22",
            12:{"reply":2,children:[],"content":"oooadfa","depth":1,"create_datetime":"2021-09-0122:32:22"},
            13:{"reply":11,children:[]"content":"gooadfa","depth":2,"create_datetime":"2021-09-01 22:32:22",
            14:{"reply":12,children:[]"content":"oooadfa","depth":2,"create_datetime":"2021-09-0122:32:22"],
            15:{"reply":13,children:[]"content":"gooadfa","depth":3,"create_datetime":"2021-09-01 22:32:22"],
            16:{"reply":15,children:[]"content":"oooadfa","depth":4,"create_datetime":"2021-09-0122:32:22"],
        }
        """
        for descendant in descendant_queryset:
            ser = CreateCommentSerializers(instance=descendant, many=False)  # 构造序列化器
            row = {'children': []}
            row.update(ser.data)
            descendant_dict[descendant.id] = row
        # print(descendant_dict)

        # 根评论obj的1级评论
        children_list = [
              # {"reply": 2, children:[],"content": "oooadfa","depth": 1, "create_datetime": "2021-09-01 22:32:22"},
     
              # {"reply": 2, children:[],"content": "oooadfa","depth": 1, "create_datetime": "2021-09-01 22:32:22"}
              ]
        for cid, item in descendant_dict.items():
            depth = item['depth']  # 获取评论深度
            if depth == 1:  # 将一级评论插入列表,[{'children': [],'reply': 2......],
                children_list.append(item)
                continue
            reply_id = item['reply']  # 获取回复了一级评论的那条评论reply_id,并将该条评论插入到一级评论的children列表中
            descendant_dict[reply_id]['children'].append(item)
        return children_list

posted @ 2022-08-31 12:06  晚点心动。  阅读(110)  评论(0)    收藏  举报