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
添加回答
舉報