Django序列化器方法字段 [英] Django Serializer Method Field

查看:167
本文介绍了Django序列化器方法字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎找不到合适的谷歌搜索工具,因此就可以了:

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)

,它计算所有相关字段 post。

which counts all the related field "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

这可能吗?

推荐答案

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

assuming post.count is 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:

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

在您的模型中:

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

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

then use a generic Field to reference it in your serializer:

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

这篇关于Django序列化器方法字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆