python - Django 为计算字段计算 Avg

标签 python django django-models django-rest-framework

我有一个模型如下。

class Transaction(models.Model):

    time1 = models.DateTimeField(null=True)
    time2 = models.DateTimeField(null=True)

    @property
    def time_diff(self):
        return time2.total_seconds() - time1.total_seconds()

如果两个值都不为空,我需要以秒为单位获取记录列表的 (time2 - time1) 的平均值。

time_avg = transactions.aggregate(total=Avg('time_diff',field='time_diff'))

这给出了一个错误,指出“time_diff”不是一个有效的字段。我想将此列保留为派生属性。不是存储列。

最佳答案

你首先需要找到差异,然后取平均。您可以像这样使用 django F 函数。

from django.db.models import F    
result = Transaction.objects.filter('your_filter_here').annotate(time_diff=F('time1')-F('time2')).aggregate(Avg('time_diff'))

关于python - Django 为计算字段计算 Avg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48691352/

相关文章:

django - 如何从 Django 表单中删除必需的属性

python - 在 Django 中为单个产品创建页面

python - 如何使用 xdebug 和 sublime 来调试 python 脚本

python - 在 Python 2.5 中使用 with 语句 : SyntaxError?

python - Django:使 ForeignKey 不创建反向引用

python - Django makemessages 决定评论已经存在的翻译

django 'thumbnail' 不是有效的标签库 :

python - 从 urllib3.util.ssl_ 导入(导入错误 : cannot import name ssl

python - python中的for语句

django - 通过中间类保存 ManyToMany