Django Serializer方法字段

时间:2014-06-15 20:49:28

标签: python django django-rest-framework

似乎找不到合适的谷歌搜索,所以在这里:

我的序列化程序中有一个字段:

likescount = serializers.IntegerField(source='post.count', read_only=True)

计算所有相关字段“post”。

现在我想将该字段用作我方法的一部分:

def popularity(self, obj):
        like = self.likescount
            time = datetime.datetime.now()
            return like/time

这可能吗?

1 个答案:

答案 0 :(得分:51)

假设post.count用于衡量帖子中的喜欢数量,而您实际上并不打算在流行度方法中将整数除以时间戳,请尝试以下操作:

使用SerializerMethodField

likescount = serializers.SerializerMethodField('get_popularity')

def popularity(self, obj):
    likes = obj.post.count
    time = #hours since created
    return likes / time if time > 0 else likes

但我建议在模型中将其作为属性

在您的模型中:

@property
def popularity(self):
    likes = self.post.count
    time = #hours since created
    return likes / time if time > 0 else likes

然后使用通用Field在序列化程序中引用它:

class ListingSerializer(serializers.ModelSerializer):
    ...
    popularity = serializers.Field(source='popularity')