Django计算计算字段的平均值(Django calculate Avg for a computed field)

编程入门 行业动态 更新时间:2024-10-27 22:32:46
Django计算计算字段的平均值(Django calculate Avg for a computed field)

我有一个模型如下。

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'不是有效字段。 我想将此列保留为派生属性。 不是存储列。

I have a model as below.

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()

I need to get the average of the (time2 - time1) in seconds for a list of records, if both values are not null.

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

This gives an error saying 'time_diff' is not a valid field. I want to keep this column as a derived property. Not a stored column.

最满意答案

你首先需要找到差异,然后采取avarage。 您可以像这样使用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'))

You first need to find difference and then take avarage. You can use django F function for this like this.

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

更多推荐

本文发布于:2023-04-28 09:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1331383.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:平均值   字段   Django   calculate   field

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!