Django Rest框架如何展示单篇博客下的所有关联评论?
问题描述
我搭建了一个博客网站,访客可对博客文章进行评论。每篇博客对应多条评论,我希望在单篇博客详情页展示其所有关联评论,例如Blog1有10条评论,需全部显示在Blog1下方。
现有代码
models.py
class Blog(models.Model): blog_title = models.CharField(max_length=200, unique=True) class Comment(models.Model): name = models.CharField(max_length=100) email = models.EmailField(max_length=100) comment = models.TextField() blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
Serializer.py
class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog exclude = ("author", "blog_is_published") lookup_field = 'blog_slug' extra_kwargs = { 'url': {'lookup_field': 'blog_slug'} }
views.py
class BlogViewSet(viewsets.ModelViewSet): queryset = Blog.objects.all().order_by('-id') serializer_class = BlogSerializer pagination_class = BlogPagination lookup_field = 'blog_slug'
解决方案
要实现单篇博客详情页显示所有关联评论,按以下步骤修改代码:
- 优化模型反向关联命名(可选但推荐)
修改Comment模型的外键字段,添加related_name让反向关联更直观:
class Comment(models.Model): # 其他字段保持不变 blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='comments')
- 修改BlogSerializer,添加评论嵌套序列化
在BlogSerializer中新增嵌套字段,用于序列化关联的评论列表:
class BlogSerializer(serializers.ModelSerializer): # 新增字段,序列化当前博客的所有评论 comments = CommentSerializer(many=True, read_only=True) class Meta: model = Blog exclude = ("author", "blog_is_published") lookup_field = 'blog_slug' extra_kwargs = { 'url': {'lookup_field': 'blog_slug'} }
- 优化查询性能,避免N+1问题
在BlogViewSet的查询集中使用prefetch_related预加载所有关联评论,减少数据库查询次数:
class BlogViewSet(viewsets.ModelViewSet): # 预加载关联的评论数据 queryset = Blog.objects.all().order_by('-id').prefetch_related('comments') serializer_class = BlogSerializer pagination_class = BlogPagination lookup_field = 'blog_slug'
完成以上修改后,访问单篇博客的详情接口时,返回的JSON数据会自动包含该博客的所有评论列表,前端可直接将评论渲染在博客内容下方。
内容的提问来源于stack exchange,提问作者boyenec
相关产品推荐
相关产品推荐

