1 回答

TA贡献1859条经验 获得超6个赞
你的代码是颠倒的。被引用的实体在被引用之前需要被定义。将 CommentSerializer 类放在 PostDetailSerializer 类之前。
class CommentSerializer(serializers.ModelSerializer):
reply_count = SerializerMethodField()
author = SerializerMethodField()
class Meta:
model = Comment
fields = ('content', 'parent', 'author', 'reply_count', 'post')
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
class PostDetailSerializer(serializers.ModelSerializer):
image = SerializerMethodField()
author = SerializerMethodField()
comments = CommentSerializer(source='comments.content')
class Meta:
model = Post
fields = ('author', 'image', 'title', 'created_at','star_rate', 'slug', 'comments')
def get_image(self, obj):
try:
image = obj.image.url
except:
image = None
return image
def get_author(self, obj):
return obj.author.username
添加回答
举报