Home > OS >  <int:pk> or {pk} does not work in DRF router
<int:pk> or {pk} does not work in DRF router

Time:11-24

I have an Comment which have an Article foreign key (so Article have an "array" of comments). I need to build an url to fetch theese comments using article's pk, but when I am trying to do smth like "articles/int:article_pk/comments/" or "articles/{article_pk}/comments/" drf router crates static route with path "articles/{article_pk}/comments/". How can I implement getting a comments using article pk?

urls.py

router = DefaultRouter()
router.register('articles', articleAPI.ArticleAPI, basename='articles')
router.register('articles/comments', CommentAPI,  basename='comments')

CodePudding user response:

Its not working because that is not how routers are intended to be used. You don't specify the key when registering, you use the viewset to define it. Read the docs at [1]. [1]: https://www.django-rest-framework.org/api-guide/routers/#simplerouter

CodePudding user response:

A router can indeed not do that. You will need to capture the article_pk in the path and then work with two routers, so:

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)),
]

CodePudding user response:

You can use this same url to get comments as well.

router.register('articles', articleAPI.ArticleAPI, basename='articles')

add a new method to 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)

In postman hit the url articles/<article_id>/comments/ with GET method to get the comment list

  • Related