表数据
树状结构
@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