django 递归查询评论的示例详解
更新时间:2025年01月03日 09:47:37 作者:像风一样的男人@
文章介绍了将表数据转换为树状结构以及如何处理扁平化数据的方法,探讨了在数据管理中的应用和实现技术,感兴趣的朋友一起看看吧
表数据
树状结构
@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 评论内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
浅谈SpringMVC HandlerInterceptor诡异问题排查
这篇文章主要介绍了浅谈SpringMVC HandlerInterceptor诡异问题排查,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2019-05-05
最新评论