我有一个评论有一个文章外键(所以文章有一个"数组"的评论)。我需要建立一个url来获取这些评论使用文章的pk,但当我试图做类似"文章/int:article_pk/评论/"或者"文章/{article_pk}/评论/"DRF路由器装箱静态路由,路径"articles/{article_pk}/comments/"我如何使用文章pk实现获得评论?
urls . py
router = DefaultRouter()
router.register('articles', articleAPI.ArticleAPI, basename='articles')
router.register('articles/comments', CommentAPI, basename='comments')
您也可以使用相同的url来获取评论。
router.register('articles', articleAPI.ArticleAPI, basename='articles')
为Article
ModelViewSet添加一个新方法
@action(methods=['get'], detail=True,
url_path='comments', url_name='article-comments')
article = self.get_object()
serializer = CommentSerializer(queryset=article.comment_set.all(), many=True) # comment_set resembles the related name for article foreign key
return Response(serializer.data)
在邮差点击urlarticles/<article_id>/comments/
与GET方法获得评论列表
它不起作用,因为这不是路由器的预期使用方式。注册时不指定键,而是使用视图集来定义键。阅读文档[1]。[1]: https://www.django-rest-framework.org/api-guide/routers/simplerouter
路由器确实做不到这一点。您将需要捕获path
中的article_pk
,然后使用两个路由器,因此:
article_router = DefaultRouter()
article_router.register('articles', articleAPI.ArticleAPI, basename='articles')
comment_router = DefaultRouter()
comment_router.register('comments', CommentAPI, basename='comments')
urlpatterns = [
path('', include(article_router.urls)),
path('articles/<int:article_pk>/', include(comment_router.urls)),
]