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'))更多推荐
发布评论