java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > django 评论

django 递归查询评论的示例详解

作者:像风一样的男人@

文章介绍了将表数据转换为树状结构以及如何处理扁平化数据的方法,探讨了在数据管理中的应用和实现技术,感兴趣的朋友一起看看吧

表数据

树状结构

@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

扁平化处理

@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

到此这篇关于django 递归查询评论的示例详解的文章就介绍到这了,更多相关django 评论内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文