You need to enable JavaScript to run this app. 基于GenericViewSet/ModelMixins实现带URL ID参数的文章评论嵌套API
优惠活动
大模型
产品
解决方案
定价
更多

基于GenericViewSet/ModelMixins实现带URL ID参数的文章评论嵌套API

基于GenericViewSet实现文章嵌套评论API的配置方法

前置准备

  • 首先确认模型关联符合要求:Comment模型中通过ForeignKey关联Article时,务必设置反向查询的related_name,示例写法:
    article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name="comments")
  • 编写Comment的序列化器,将关联的Article字段设置为只读——因为这个字段的取值来自URL参数,不需要前端通过请求体传递,避免篡改:
    class CommentSerializer(serializers.ModelSerializer):
        class Meta:
            model = Comment
            fields = ["id", "content", "created_at", "article"]
            read_only_fields = ["article"]
    

视图核心逻辑实现

我们可以直接用DRF内置的ListModelMixin、CreateModelMixin搭配GenericViewSet完成需求,不需要自定义复杂的逻辑,核心要补两个环节的处理:

  1. 重写get_queryset()方法,根据URL携带的文章ID过滤评论数据
    GenericViewSet会自动把URL路径中捕获的参数存到self.kwargs字典中,我们直接从这里取文章ID,过滤出对应文章下的所有评论即可:
    from django.shortcuts import get_object_or_404
    from rest_framework import mixins, viewsets
    from .models import Article, Comment
    from .serializers import CommentSerializer
    
    class CommentViewSet(mixins.ListModelMixin,
                        mixins.CreateModelMixin,
                        viewsets.GenericViewSet):
        serializer_class = CommentSerializer
    
        def get_queryset(self):
            # 从URL捕获的参数中取出文章ID
            article_id = self.kwargs.get("article_pk")
            # 只返回当前文章关联的评论,避免泄露其他文章的评论数据
            return Comment.objects.filter(article_id=article_id)
    
  2. 重写perform_create()方法,新建评论时自动绑定文章ID
    因为序列化器里的article字段是只读的,我们需要在保存评论实例的时候,手动把URL里对应的Article对象绑定到新建的评论上,不需要前端传值:
    class CommentViewSet(...): # 延续上面的类定义
        def perform_create(self, serializer):
            article_id = self.kwargs.get("article_pk")
            # 先校验文章是否存在,不存在直接返回404
            article = get_object_or_404(Article, id=article_id)
            # 把文章对象传入序列化器完成保存
            serializer.save(article=article)
    

路由配置匹配目标URL格式

只需要把视图的list、create动作绑定到你要的嵌套路径上即可,这里有两种常用配置方式:

  • 零依赖手动配置路由
    不需要额外安装第三方库,直接在项目urls.py中编写路径,注意URL路径里捕获的参数名,必须和视图里从self.kwargs取的key完全一致,否则会出现参数取不到的问题:
    from django.urls import path
    from .views import CommentViewSet
    
    # 绑定视图集的HTTP方法对应关系
    comment_endpoint = CommentViewSet.as_view({
        "get": "list",
        "post": "create"
    })
    
    urlpatterns = [
        # 路径捕获的参数名是article_pk,和视图取值逻辑对应
        path("article/<int:article_pk>/comments", comment_endpoint, name="article-comments")
    ]
    
  • 嵌套路由器自动生成路由
    如果项目中嵌套类接口比较多,可以使用DRF生态的嵌套路由器自动生成符合格式的路径,生成的路径默认捕获参数名就是article_pk,和我们写的视图逻辑完全匹配,不需要手动调整参数名。

常见问题排查

  • 如果请求返回了所有文章的评论,说明没有重写get_queryset()做按文章ID过滤,直接用了全局的Comment查询集
  • 如果新建评论时报关联字段为空的错误,说明没有在perform_create()里把URL取到的Article对象传给保存方法
  • 如果出现权限绕过、前端可以给其他文章写评论的问题,检查序列化器里的article字段是不是误设为可写了

内容的提问来源于stack exchange,提问作者Yusuf Selim KARATAS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.23 14:36:03