简体   繁体   English

django rest 框架评论系统

[英]django rest framework comment system

I am trying to build a rest api with django and having hard times with comment system.我正在尝试使用 django 构建 rest api 并且在评论系统方面遇到困难。 The API shows my comments correctly but it shows replies to comments twice. API 正确显示了我的评论,但它显示了对评论的两次回复。 One at comments field of post, other at replies field of comments.一个在帖子的评论字段,另一个在评论的回复字段。 Like both in depth 1 and 2. So to cut short, there is my code:就像深度 1 和 2 一样。所以简而言之,有我的代码:

-- serializers.py --序列化器.py

class CommentChildSerializer(serializers.ModelSerializer):
    parent_id = serializers.PrimaryKeyRelatedField(queryset=Comment.objects.all(),source='parent.id')
    author = SerializerMethodField()
    class Meta:
        model = Comment
        fields = ('author', 'content', 'id','parent_id')

    def get_author(self, obj):
        return obj.author.username

    def create(self, validated_data):
        subject = parent.objects.create(parent=validated_data['parent']['id'], content=validated_data['content'])

class CommentSerializer(serializers.ModelSerializer):
    reply_count = SerializerMethodField()
    author = SerializerMethodField()
    replies = SerializerMethodField()
    class Meta:
        model = Comment
        fields = ('id','content', 'parent', 'author', 'reply_count', 'replies')
        # depth = 1

    def get_reply_count(self, obj):
        if obj.is_parent:
            return obj.children().count()
        return 0

    def get_author(self, obj):
        return obj.author.username

    def get_replies(self, obj):
        if obj.is_parent:
            return CommentChildSerializer(obj.children(), many=True).data
        return None

class PostListSerializer(serializers.ModelSerializer):
    url = post_detail_url
    author = SerializerMethodField()
    image = SerializerMethodField()
    comments = CommentSerializer(required=False, many=True)
    # comments = SerializerMethodField()
    class Meta:
        model = Post
        fields = ('title', 'image', 'author', 'star_rate', 'url', 'slug', 'comments')

    def get_author(self, obj):
         return obj.author.username

    def get_image(self, obj):
        try:
            image = obj.image.url
        except:
            image = None
        return image

-- comment model --评论 model

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
    author = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    content = models.TextField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='replies')
    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ('created_at',)

    def __str__(self):
        return f'Comment by {self.author.username} on {self.post}'

    def children(self):
        return Comment.objects.filter(parent=self)

    @property
    def is_parent(self):
        if self.parent is not None:
            return False
        return True

What does your view look like?你的观点是什么样的? If you want only comments with no parent to display as top-level comments, then you'll need to make sure that the queryset populating your serializer filters appropriately, eg Comment.objects.filter(parent__isnull=True)如果您只希望没有父级的评论显示为顶级评论,那么您需要确保填充序列化程序的查询集适当地过滤,例如Comment.objects.filter(parent__isnull=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM