DjangoRestFramework - 如何根据最终用户输入过滤ViewSet的对象列表?

时间:2015-11-10 00:29:56

标签: django django-rest-framework

这是我的ViewSet:

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.order_by('-createdAt')
    serializer_class = PostSerializer
    permission_classes = (IsAuthenticated, IsLikeOrOwnerDeleteOrReadOnly,)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user, location=self.request.user.userextended.location)

    def get_serializer_context(self):
            """
            Extra context provided to the serializer class.
            """
            return {
                'request': self.request,
                'format': self.format_kwarg,
                'view': self,
                'location': self.request.user.userextended.location
            }

    @detail_route(methods=['post'], permission_classes=[IsFromLocationOrReadOnly])
    def like(self, request, pk=None):
        post = self.get_object()
        post.usersVoted.add(request.user)
        return Response(status=status.HTTP_204_NO_CONTENT)

这是我的路由器/ urls.py

router = routers.DefaultRouter()
router.register(r'posts', views.PostViewSet)

所以当我去/posts时,我会得到所有帖子的列表。我想要的是能够允许最终用户转到特定的URL,如下所示:/posts/username当他这样做时,我想给他所有特定用户名的帖子(过滤将很简单这些方面的东西:

queryset = Post.objects.filter(username=usernameProvidedByTheURL)

我该怎么做呢?是否可以使用DRF?

1 个答案:

答案 0 :(得分:1)

在你的网址中:

url(r'^/post/(?P<username>\w+)/?$', PostViewSet.as_view({'get': 'list'})),

然后在PostViewSet中,覆盖get_queryset()方法,按username

过滤数据
class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.order_by('-createdAt')
    serializer_class = PostSerializer
    permission_classes = (IsAuthenticated, IsLikeOrOwnerDeleteOrReadOnly,)

    def get_queryset(self):
        username = self.kwargs['username']
        return Post.objects.filter(username=username)

<强>更新

如果您想保留/post/端点以检索所有帖子。然后,您需要创建一个额外的视图来处理/post/username

class PostsListByUsername(generics.ListAPIView):
    serializer_class = PostSerializer

        def get_queryset(self):
            username = self.kwargs['username']
            return Post.objects.filter(username=username)

然后在你的urls.py

url(r'^/post/(?P<username>\w+)/?$', PostsListByUsername.as_view()),

注意: 在get_serializer_context方法中,您无需返回requestformatview。 DRF将为您追加。

def get_serializer_context(self):
        """
        Extra context provided to the serializer class.
        """
        return {
            'location': self.request.user.userextended.location
        }