the list method returning a post for specific id I sent as pk, not for author id,
I can write another method with get action to get posts that I want , but I really want to know why this is not working
I ask whether its returning a post or a queryset containing a post because this comment is ambiguous. The list method (from ModelViewSet and in your subclass) should always return a queryset so if it’s returning a single post then the list method is not being called.
I would try confirming that your list method is actually being called by printing some debug information to the console, eg:
def list(self, request, pk):
post = Post.objects.filter(author=pk)
print("custom list method is called")
if post:
serializer = PostSerializers(post, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
else:
response = {"message": "the author has no posts"}
return Response(response, status=status.HTTP_404_NOT_FOUND)
It would also be useful to know what request you are making to test this functionality.
The best way to do this is to use nested routers and have an url structure like:
/authors/ <--- list of authors
/articles/ <--- this gives a list of articles
/authors/1234 <--- the author with the id 1234
/authors/1234/articles <--- articles by the author with id 1234
github / drf-nested-routers for nested routers. Then your get_queryset will look like:
def get_queryset(self):
queryset = Post.objects.all()
if 'author_id' in self.kwargs:
queryset = queryset.filter(
author=self.kwargs.pop('author_id')
)
return queryset
In any case, you don’t need to override the list function.
I tried to confirm list method , it is not printing anything in the console, so I think it is not being called,
and it is returning only single post , http://127.0.0.1:8000/post/2/
this is my request,…