Nesting Routes for the Comment Resource
Implement nested routing for posting and retrieving comments under posts.
Now that the comment serializer is ready, we can proceed to write the viewsets concerning the comment feature. But before that, let’s talk about the endpoint of the resource.
To create, update, or delete comments, we need to add ViewSet
. In the comment directory, create a file called viewsets.py
. This file will contain the code for the
CommentViewSet
class. We won’t be writing all the code for this viewset because we need to get some clear ideas on the structure of the endpoint.
So, add the following content for the moment:
from django.http.response import Http404from rest_framework.response import Responsefrom rest_framework import statusfrom core.abstract.viewsets import AbstractViewSetfrom core.comment.models import Commentfrom core.comment.serializers import CommentSerializerfrom core.auth.permissions import UserPermissionclass CommentViewSet(AbstractViewSet):http_method_names = ('post', 'get', 'put', 'delete')permission_classes = (UserPermission,)serializer_class = CommentSerializer...
Endpoint architecture
Great, now let’s talk about the endpoint architecture. The following table shows the structure of the endpoint concerning the comment. We have the method, the URL of the endpoint, and finally, the result of a call on this endpoint:
Comment endpoint structure
Method | URL | Result |
|
| Lists all the comments related to a post |
|
| Retrieves a specific comment |
|
| Creates a comment |
|
| Modifies a comment |
|
| Deletes a comment |
However, for the comment feature, we are working with posts. And it’s definitely a great idea if comments are directly related to posts. Therefore, a great structure for our endpoints would look like this:
Comment endpoint structure—nested
Method | URL | Result |
|
| Lists all the comments related to a post |
|
| Retrieves a specific comment |
|
| Creates a comment |
|
| Modifies a comment |
|
| Deletes a comment |
In this structure, the endpoint is nested, meaning that comment resources live under post resources.
But how do we achieve this simply?
The Django ecosystem has a library called ...