我希望用嵌套资源实现我的新API。
Example: /api/users/:user_id/posts/
将评估特定用户的所有帖子。我还没有看到这个用例的工作示例,也许这不是实现rest API的正确方法?
正如Danilo所评论的那样,@link
装饰器被移除,有利于@list_route
和@detail_route
装饰。
@detail_route
& @list_route
got deprecated in favor of @action
.这是替代解决方案:
@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)
试试drf-nested-routers
。尚未尝试过,但看起来很有希望,许多人已经在使用它。看起来像我们已经尝试实现的高级版本。
希望这可以帮助。
要映射/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)
作为commented by Danilo Cabello早些时候你会使用@detail_route
或@list_route
而不是@link()
。有关详细说明,请阅读"Routers", section "Extra link and actions"和"ViewSets", section "Marking extra actions for routing"的文档。