我需要得到这个端点 /comments/int:post_id/ 我可以获取和发布评论和帖子,但我需要显示特定帖子的所有评论。我不知道如何连接它。我的代码看起来像
评论网址
urlpatterns = [
path('', views.CommentsView.as_view()),
path('<int:post_id>/', views.CreateCommentsView.as_view()),
]
评论view.py
# I get all comments/
class CommentsView(ListCreateAPIView):
queryset = Comment.objects.all()
serializer_class = CommentSerializer
# Comments to specific post
class CreateCommentsView(ListCreateAPIView):
queryset = Comment.objects.all()
serializer_class = CommentSerializer
lookup_url_kwarg = 'post_id'
def perform_create(self,serializer):
post = self.kwargs.get('post_id')
post =set.get_queryset().filter(id = 'post_id')
post.comments.add(comment)
post = Post.objects.filter(id=self.kwargs.get('post_id'))
serializer.save(user=self.request.user, post=post)
注释序列化器
from rest_framework import serializers
from .models import Comment
from django.contrib.auth import get_user_model
User = get_user_model()
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = ['id', 'user', 'post', 'content', 'created']
class UserSimpleSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['username']
class CommentSimpleSerializer(serializers.ModelSerializer):
user = UserSimpleSerializer()
class Meta:
model = Comment
fields = ['user', 'content', 'created']
post.view.py
class PostList(generics.ListCreateAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer
class PostDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer
class LikePost(generics.UpdateAPIView):
permission_classes = [IsNotPostUser]
queryset = Post.objects.all()
serializer_class = PostSerializer
答案 0 :(得分:0)
您可以在 post_id
端点的 url 参数中传递 /comments/
并调用 HTTP GET 方法。然后在 CommentsView
中,您需要覆盖 get_queryset
方法。您的实施将类似于
class CommentsView(ListCreateAPIView):
serializer_class = CommentSerializer
def get_queryset(self):
query = self.request.query_params.get('post_id', None)
if query is not None:
queryset = Comment.objects.filter(post_id=post_id)
else:
queryset = Comment.objects.all()
return queryset
此 /comments/
端点将返回所有评论,而此 /comments/?post_id=1
端点将仅返回与指定帖子相关的评论。