I have this model:
我有这个型号:
class TimeInterval(models.Model):
startTime = models.DateTimeField()
endTime = models.DateTimeField()
How can I aggregate average time interval using only the QuerySet API?
如何仅使用QuerySet API聚合平均时间间隔?
I tried this:
我试过这个:
qs = TimeInterval.objects.extra(
select={"duration": "endTime - startTime"}).aggregate(
Avg("duration"))
but it throws:
但它抛出:
FieldError: Cannot resolve keyword 'duration' into field. Choices are:
endTime, startTime
1 个解决方案
#1
1
I'll use a workaround for this.
我将使用解决方法。
Create a new field called duration.
创建一个名为duration的新字段。
Create a pre-save_signal for TimeInterval that would calculate the value for duration.
为TimeInterval创建一个pre-save_signal,用于计算持续时间的值。
Then, you can easily use the duration field in your queries.
然后,您可以在查询中轻松使用持续时间字段。
#1
1
I'll use a workaround for this.
我将使用解决方法。
Create a new field called duration.
创建一个名为duration的新字段。
Create a pre-save_signal for TimeInterval that would calculate the value for duration.
为TimeInterval创建一个pre-save_signal,用于计算持续时间的值。
Then, you can easily use the duration field in your queries.
然后,您可以在查询中轻松使用持续时间字段。