问题
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