Now I have tried to use nested routers to solve the issue but still Iwant to be able to create new comments without sending the blog post ID from the request body. I want to be able to get it from request parameters. So, how can I get this id one and use it to create new comment
http://127.0.0.1:8000/blog-posts/1/comments/
My routes looks like this.
from rest_framework_extensions.routers import NestedRouterMixin
class NestedDefaultRouter(NestedRouterMixin, DefaultRouter):
pass
router = NestedDefaultRouter()
blog_posts_router = router.register('blog-posts', BlogPostViewSet)
blog_posts_router.register(
'comments',
CommentViewSet,
base_name='comments',
parents_query_lookups=['blog_post']
)
urlpatterns = [
path('', include(router.urls))
]
and this is how my Views are looking like
from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from .models import BlogPost, Comment
from .serializers import BlogPostSerializer, CommentSerializer
from rest_framework.decorators import action
from django.http import JsonResponse
import json
from rest_framework_extensions.mixins import NestedViewSetMixin
class BlogPostViewSet(NestedViewSetMixin, ModelViewSet):
""" Handles creating, updating, listing and deleting blog posts. """
serializer_class = BlogPostSerializer
queryset = BlogPost.objects.all()
class CommentViewSet(NestedViewSetMixin, ModelViewSet):
""" Handles creating, updating, listing and deleting comments on blog posts. """
serializer_class = CommentSerializer
queryset = Comment.objects.all()
Thank you I'm waiting for your help. I couldn't find it from the documentations