Django REST Framework中的嵌套资源

问题描述 投票:14回答:3

我希望用嵌套资源实现我的新API。

Example: /api/users/:user_id/posts/

将评估特定用户的所有帖子。我还没有看到这个用例的工作示例,也许这不是实现rest API的正确方法?

python django rest django-rest-framework nested-resources
3个回答
21
投票

正如Danilo所评论的那样,@link装饰器被移除,有利于@list_route@detail_route装饰。

Update: @detail_route & @list_route got deprecated in favor of @action.

这是替代解决方案:

解决方案1:

@detail_route()
def posts(self, request, pk=None):
    owner = self.get_object()
    posts = Post.objects.filter(owner=owner)

    context = {
        'request': request
    }

    post_serializer = PostSerializer(posts, many=True, context=context)
    return Response(post_serializer.data)

解决方案2:

试试drf-nested-routers。尚未尝试过,但看起来很有希望,许多人已经在使用它。看起来像我们已经尝试实现的高级版本。

希望这可以帮助。


4
投票

要映射/api/users/:user_id/posts/你可以用你的posts装饰ViewSet里面的@link()方法

from rest_framework.decorators import link


class UserViewSet(viewsets.ModelViewSet):
    model = User
    serializer_class = UserSerializer

    # Your regular ModelViewSet things here

    # Add a decorated method like this
    @link()
    def posts(self, request, pk):
        # pk is the user_id in your example

        posts = Post.objects.filter(owner=pk)    

        # Or, you can also do a related objects query, something like:
        # user = self.get_object(pk)
        # posts = user.post_set.all()

        # Then just serialize and return it!
        serializer = PostSerializer(posts)
        return Response(serializer.data)

2
投票

作为commented by Danilo Cabello早些时候你会使用@detail_route@list_route而不是@link()。有关详细说明,请阅读"Routers", section "Extra link and actions""ViewSets", section "Marking extra actions for routing"的文档。

© www.soinside.com 2019 - 2024. All rights reserved.