Search code examples
pythondjangorestdjango-rest-frameworknested-resources

Nested resources in Django REST Framework


I wish to implement my new API with a nested resource.

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

Will evaluate to all of the posts for a specific user. I haven't seen an working example for this use case, maybe this isn't the right way for implementing rest API?


Solution

  • As commented by Danilo, the @link decorator got removed in favor of @list_route and @detail_route decorators.

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

    Here's the alternate solutions:

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

    Solution 2:

    Try drf-nested-routers. Haven't tried this out yet, but looks promising, many are already using it. Looks like an advanced version of what we are already trying to achieve.

    Hope this helps.