DRF路由中<int:pk>或{pk}不生效,如何通过文章主键获取评论?
如何通过文章主键获取关联评论(DRF路由配置)
你当前的路由注册方式会把comments当成独立资源,生成静态路径articles/comments/,无法关联具体文章主键。以下是两种可行的解决方法:
方法一:自定义ViewSet Action
在CommentAPI ViewSet中添加自定义action,通过URL参数接收文章主键并过滤评论:
from rest_framework.decorators import action from rest_framework.response import Response class CommentAPI(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer @action(detail=False, methods=['get'], url_path='by-article/(?P<article_pk>[0-9]+)') def get_comments_by_article(self, request, article_pk): # 根据文章主键过滤评论 comments = self.queryset.filter(article_id=article_pk) serializer = self.get_serializer(comments, many=True) return Response(serializer.data)
路由注册保持原有配置即可,最终生成的访问路径为articles/comments/by-article/<article_pk>/,请求该路径就能获取对应文章的评论。
方法二:手动配置嵌套路由
如果想要articles/<article_pk>/comments/的URL结构,可手动配置路由并在ViewSet中动态过滤查询集:
1. 修改urls.py配置
from django.urls import path from . import articleAPI, commentAPI urlpatterns = [ # 文章相关路由 path('articles/', articleAPI.ArticleAPI.as_view({'get': 'list', 'post': 'create'})), path('articles/<int:pk>/', articleAPI.ArticleAPI.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})), # 文章评论路由 path('articles/<int:article_pk>/comments/', commentAPI.CommentAPI.as_view({'get': 'list', 'post': 'create'})), ]
2. 重写CommentAPI的get_queryset方法
class CommentAPI(viewsets.ModelViewSet): serializer_class = CommentSerializer def get_queryset(self): # 从URL参数中获取文章主键,过滤评论 article_pk = self.kwargs.get('article_pk') if article_pk: return Comment.objects.filter(article_id=article_pk) # 如果没有传文章主键,返回所有评论(可选) return Comment.objects.all()
配置完成后,访问articles/1/comments/即可获取ID为1的文章的所有评论。
注:如果不想手动配置路由,也可以使用
django-rest-framework-nested第三方包提供的NestedSimpleRouter来快速实现嵌套路由,原理与手动配置一致。
内容的提问来源于stack exchange,提问作者Sanyokk
相关产品推荐
相关产品推荐

