Aggregate in django with duration field

谁说我不能喝 提交于 2021-01-28 04:38:41

问题


My model is:

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

Some test data:

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

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

but:

Invalid connector for timedelta: *.

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.

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']), 

but

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

回答1:


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



来源:https://stackoverflow.com/questions/33237819/aggregate-in-django-with-duration-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!