[英]django rest framework comment system
我正在嘗試使用 django 構建 rest api 並且在評論系統方面遇到困難。 API 正確顯示了我的評論,但它顯示了對評論的兩次回復。 一個在帖子的評論字段,另一個在評論的回復字段。 就像深度 1 和 2 一樣。所以簡而言之,有我的代碼:
--序列化器.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
--評論 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
你的觀點是什么樣的? 如果您只希望沒有父級的評論顯示為頂級評論,那么您需要確保填充序列化程序的查詢集適當地過濾,例如Comment.objects.filter(parent__isnull=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.