在django中使用工期字段进行汇总 [英] Aggregate in django with duration field

查看:70
本文介绍了在django中使用工期字段进行汇总的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模特是:

class Mo(Model):
    dur = DurationField(default=timedelta(0))

    price_per_minute = FloatField(default=0.0)

    minutes_int = IntegerField(default=0)  # dublicates data from dur , only for test

一些测试数据:

for i in range(4):
    m = Mo(dur=timedelta(minutes=i),
           minutes_int=i,
           price_per_minute=10.0)
    m.save()

我想将 dur 乘以 price_per_minute ,然后找到 Sum :

I want to multiply the dur by price_per_minute and find Sum:

r = Mo.objects.all().aggregate(res=Sum(F('dur')*F('price_per_minute')))
print(r['res']/(10e6 * 60))

但是:

Invalid connector for timedelta: *.

说明:在数据库 DurationField 中存储为包含微秒的简单BIGINT,如果我知道如何以总计方式获取它,则将其除以(10e6 * 60)并已付款分钟.

Explanation: In database DurationField is stored as a simple BIGINT that contains micro-seconds, if I know how to obtain it in aggregate I will divide it by (10e6 * 60) and will have paid minutes.

如果我使用简单的 IntegerField ,则一切正常:

If I use a simple IntegerField instead everything works:

r = Mo.objects.all().aggregate(res=Sum(F('minutes_int')*F('price_per_minute')))
print(r['res']/(10e6*60))

因此,我需要在汇总中将某些类型转换为整数,是否可以将工期转换为一些额外的字段?

So I need some cast to integer in the aggregate, is it possible to convert duration to some extra field?

r = Mo.objects.all().extra({'mins_int': 'dur'}).aggregate(res=Sum(F('mins_int')*F('price_per_minute')))
print(r['res']), 

但是

Cannot resolve keyword 'mins_int' into field. Choices are: dur, id, minutes_int, price_per_minute

推荐答案

您可以使用 ExpressionWrapper(F('dur'),output_field = BigIntegerField())使Django对待 dur作为整数值.

You can use ExpressionWrapper(F('dur'), output_field=BigIntegerField()) to make Django treat dur as an integer value.

这篇关于在django中使用工期字段进行汇总的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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