Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate in django with duration field

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
like image 376
Ivan Borshchov Avatar asked Sep 07 '25 16:09

Ivan Borshchov


1 Answers

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

like image 140
Ivan Avatar answered Sep 09 '25 06:09

Ivan