Django Serializer方法字段

Joh*_*n D 31 python django django-rest-framework

似乎无法找到正确的谷歌搜索,所以在这里:

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

likescount = serializers.IntegerField(source='post.count', read_only=True)
Run Code Online (Sandbox Code Playgroud)

它计算所有相关字段"post".

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

def popularity(self, obj):
        like = self.likescount
            time = datetime.datetime.now()
            return like/time
Run Code Online (Sandbox Code Playgroud)

这可能吗?

tom*_*ell 62

假设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
Run Code Online (Sandbox Code Playgroud)

但是我建议你在你的模型中做一个属性

在你的模型中:

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

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

class ListingSerializer(serializers.ModelSerializer):
    ...
    popularity = serializers.Field(source='popularity')
Run Code Online (Sandbox Code Playgroud)

  • 嘿我实现了相同但有以下错误:`/ api/recipes/2 /``字段(read_only = True)的AssertionError应该是ReadOnlyField` (2认同)