假设我有以下序列化程序。
class ArticleSerializer(serializers.ModelSerializer):
comment_count = serializers.SerializerMethodField()
commented = serializers.SerializerMethodField()
def get_comment_count(self, obj):
# Assume the method can retrieve the comment count correctly
return x
def get_commented(self, obj):
# Return True if comment count > 0, else False
class Meta:
model = Article
fields = ['title', 'content', 'comment_count', 'commented']
对于 get_commented
方法中的编码有什么建议吗?我编写了类似 return comment_count > 0
的代码,但失败了。
最佳答案
您可以使用 obj 访问 django 对象,所以我认为代码应该是这样的:
obj.comment_set.count()
获取评论数,然后:
return self.get_comment_count(obj) > 0
如Pang所说的实现get_commented
关于python - Django 序列化器字段值基于同一序列化器中的其他字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29295076/