Reputation: 1735
I have a simple Blog app where anyone can add post and comment to post.
Comments have forignkey relationship with Post.
When I select url patch posts/<post id>/comments
it shows all comments instead of the comments from related posts. All other CRUD functions works fine with the project.
The Git Link :https://github.com/Anoop-George/DjangoBlog.git
The problem occurs in view.py where comment object unable to filter comments which are related to specific posts.
class CommentListCreate(APIView):
def get(self, request,pk):
**comment = Comment.objects.filter()** # I need filter here
serializer = CommentSerializers(comment, many=True)
return Response(serializer.data)
Upvotes: 0
Views: 25
Reputation: 372
First of all, don't use space in url argument
or in general in urls. Url patch should be posts/<int:post_id>/comments
.
Now, your class view looks like:
class CommentListCreate(APIView):
def get(self, request, *args, **kwargs):
id = kwargs.get("post_id", None)
comment = Comment.objects.filter(post__id=id)
serializer = CommentSerializers(comment, many=True)
return Response(serializer.data)
I didn't get a chance to verify it but I am pretty sure it will work.
Upvotes: 1