django --递归查询评论

表数据

树状结构

python 复制代码
@action(methods=('GET', ), detail=False)
def get_info_pinglun(self, request, *args, **kwargs) -> Response:
    '''
    根据评论id查所有回复
    @params  wenxian_pinglun_id   -->  评论id;
    '''
    wenxian_pinglun_id = self.request.GET.get('wenxian_pinglun_id')
    results = self._recursion_get_reply(wenxian_pinglun_id)

    return Response({
        'code': 0,
        'msg': 'success',
        'results': results
    })

def _recursion_get_reply(self, wenxian_pinglun_id: int):
    '''递归查该评论底下的所有回复'''
    results = []
    queryset = WenxianPinglun.objects.filter(other_pinglun_id=wenxian_pinglun_id) # 获取该评论下所有回复

    for instance in queryset:
        user = User.objects.get(user_id=instance.user_id)
        other = User.objects.get(user_id=instance.other_id)
        results.append({
            'wenxian_pinglun_id': instance.wenxian_pinglun_id,
            'user__img': user.img,
            'user__nicheng': user.nicheng,
            'other__nicheng': other.nicheng,
            'text': instance.text,
            'children': self._recursion_get_reply(instance.wenxian_pinglun_id)
        })
    return results

扁平化处理

python 复制代码
@action(methods=('GET', ), detail=False)
def get_info_pinglun(self, request, *args, **kwargs) -> Response:
    '''
    根据评论id查所有回复
    @params  wenxian_pinglun_id   -->  评论id;
    '''
    wenxian_pinglun_id = self.request.GET.get('wenxian_pinglun_id')
    results = self._recursion_get_reply(wenxian_pinglun_id)

    return Response({
        'code': 0,
        'msg': 'success',
        'results': results
    })

def _recursion_get_reply(self, wenxian_pinglun_id: int):
    '''递归查该评论底下的所有回复'''
    results = []
    queryset = WenxianPinglun.objects.filter(other_pinglun_id=wenxian_pinglun_id) # 获取该评论下所有回复

    for instance in queryset:
        user = User.objects.get(user_id=instance.user_id)
        other = User.objects.get(user_id=instance.other_id)
        results.append({
            'wenxian_pinglun_id': instance.wenxian_pinglun_id,
            'user__img': user.img,
            'user__nicheng': user.nicheng,
            'other__nicheng': other.nicheng,
            'text': instance.text
        })

    for instance in queryset:
        results.extend(self._recursion_get_reply(instance.wenxian_pinglun_id))
    return results
相关推荐
q***46529 小时前
Win10下安装 Redis
数据库·redis·缓存
叫致寒吧10 小时前
Tomcat详解
java·tomcat
p***924811 小时前
深入理解与实战SQL IFNULL()函数
数据库·sql·oracle
q***816413 小时前
MySQL:数据查询-limit
数据库·mysql
p***924813 小时前
DBeaver连接本地MySQL、创建数据库表的基础操作
数据库·mysql
S***267514 小时前
基于SpringBoot和Leaflet的行政区划地图掩膜效果实战
java·spring boot·后端
马剑威(威哥爱编程)14 小时前
鸿蒙6开发视频播放器的屏幕方向适配问题
java·音视频·harmonyos
JIngJaneIL14 小时前
社区互助|社区交易|基于springboot+vue的社区互助交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·社区互助
晚风吹人醒.14 小时前
缓存中间件Redis安装及功能演示、企业案例
linux·数据库·redis·ubuntu·缓存·中间件