有没有一种方法可以使用 Django 休息框架只获得一篇特定文章的评论?

Is there a way I can get comments for only one specific article using Django rest framework?

现在我已尝试使用嵌套路由器来解决问题,但我仍然希望能够创建新评论而无需从请求正文发送博客 post ID。我希望能够从请求参数中获取它。 那么,我怎样才能得到这个 id 并用它来创建新评论

http://127.0.0.1:8000/blog-posts/1/comments/

我的路线是这样的。


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

这就是我的视图的样子

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()

谢谢您,我正在等待您的帮助。我无法从文档中找到它

你可以做的是继承viewset的create函数并使用kwarg参数来访​​问post的id。然后将 post id 添加到请求数据,然后再将其传递给序列化程序并使用它来创建新对象。

 def create(self, request, *args, **kwargs):
    post_id = kwargs['parent_lookup_post']
    new_data = request.data.copy()
    new_data['post'] = post_id
    serializer = self.get_serializer(data=new_data)
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)
    headers = self.get_success_headers(serializer.data)
    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)