在Django restframework中为相关字段创建一个视图

时间:2020-06-27 15:54:30

标签: django django-rest-framework

如何在帖子的RetrieveUpdateDestroyAPIView中为评论创建视图? 至此,我将所有评论放回到列表中,无法创建一个。 我知道我可以有一个单独的CreateApiView for Comment模型并手动传递帖子的pk。但是我该怎么做是后期细节视图?谢谢。

我的帖子模型:

class Post(models.Model):
    title = models.CharField(max_length=250)
    body = models.TextField()
    [...]

我的评论模型:

class Comment(models.Model):
    post = models.ForeignKey(
        to=Post,
        on_delete=models.CASCADE,
        related_name='comments'
    )
    name = models.CharField(max_length=80)
    email = models.EmailField()
    [...]

发布详细序列化程序类:

class PostDetailSerializer(serializers.HyperlinkedModelSerializer):
    author = serializers.ReadOnlyField(source='author.username')
    tags = TagListSerializerField()
    category = serializers.SlugRelatedField(queryset=Category.objects.all(), slug_field='name')
    comments = CommentSerializer(many=True, read_only=True)

    class Meta:
        model = Post
        fields = [
            'title',
            'comments',
        ]

和发布详细信息视图

class PostDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Post.published.all()
    serializer_class = PostDetailSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]

0 个答案:

没有答案