Django如何查询自关联评论模型的嵌套树形结构?
方案1:单次查询+内存组装(推荐,性能最优)
只需要查询1次数据库,无需递归,适合任意层级的评论结构,代码逻辑简单易理解:
# 替换参数里的blog_id为你要查询的博客ID all_comments = list(Comment.objects.filter(blog_id=1).values()) # 构建ID到评论的映射,提前初始化children字段 comment_mapping = {item['id']: {**item, 'children': []} for item in all_comments} tree_result = [] for comment in all_comments: current_id = comment['id'] parent_id = comment['parent_id'] if parent_id is None: # 顶级评论直接加入结果列表 tree_result.append(comment_mapping[current_id]) else: # 子评论追加到对应父评论的children数组中 comment_mapping[parent_id]['children'].append(comment_mapping[current_id])
运行后tree_result就是你需要的目标结构,和你给出的示例输出完全一致。
方案2:基于Django ORM预取的实现
利用你模型中已经定义的related_name="children"关联关系,适合层级较少的评论场景:
def format_comment(comment_obj): return { 'id': comment_obj.id, 'user_id': comment_obj.user_id, 'blog_id': comment_obj.blog_id, 'parent_id': comment_obj.parent_id, 'content': comment_obj.content, 'children': [format_comment(child) for child in comment_obj.children.all()] } # 查询指定博客的顶级评论,prefetch_related会一次性预加载所有子评论,避免N+1查询 top_comments = Comment.objects.filter(blog_id=1, parent=None).prefetch_related('children') tree_result = [format_comment(c) for c in top_comments]
如果后续你的评论量级大幅提升、层级很深,也可以考虑引入django-mptt第三方库优化树形结构的查询性能,当前场景下上述两种原生实现已经完全够用。
内容的提问来源于stack exchange,提问作者januw a
相关产品推荐
相关产品推荐

