Python Django 序列化程序方法字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24233988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:16:44  来源:igfitidea点击:

Django Serializer Method Field

pythondjangodjango-rest-framework

提问by John D

Can't seem to find the right google search for this so here it goes:

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

I have a field in my serializer:

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

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

which counts all the related field "post".

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

Now I want to use that field as part of my method:

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

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

Is this possible?

这可能吗?

采纳答案by tomcounsell

assuming post.countis being used to measure the number of likes on a post and you don't actually intend to divide an integer by a timestamp in your popularity method, then try this:

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

use a SerializerMethodField

使用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

however I would recommend making this a property in your model

但是我建议将其作为您模型中的一个属性

in your model:

在您的模型中:

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

then use a generic Fieldto reference it in your serializer:

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

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