Django DefaultRouter 和 ViewSets 问题
Django DefaultRouter and ViewSets question
我有这条路线:
router.register(r'posts/(?P<post_id>\d+)/comments', views.CommentViewSet)
如何在 CommentViewSet class 中获取 post_id?
更新:
views.py
class CommentViewSet(viewsets.ModelViewSet):
queryset = Comment.objects.all()
serializer_class = CommentSerializer
permission_classes = (MyPremmission,)
def get_queryset(self):
queryset = self.queryset.filter(post__id = post_id)
return queryset
def perform_update(self, serializer):
serializer.save(author=self.request.user)
试试这个
def get_queryset(self):
post_id = self.kwargs.get('post_id')
queryset = self.queryset.filter(post__id = post_id)
return queryset
我有这条路线:
router.register(r'posts/(?P<post_id>\d+)/comments', views.CommentViewSet)
如何在 CommentViewSet class 中获取 post_id?
更新:
views.py
class CommentViewSet(viewsets.ModelViewSet):
queryset = Comment.objects.all()
serializer_class = CommentSerializer
permission_classes = (MyPremmission,)
def get_queryset(self):
queryset = self.queryset.filter(post__id = post_id)
return queryset
def perform_update(self, serializer):
serializer.save(author=self.request.user)
试试这个
def get_queryset(self):
post_id = self.kwargs.get('post_id')
queryset = self.queryset.filter(post__id = post_id)
return queryset