如何计算Django中两个日期之间的平均差? [英] How do I calculate the average difference between two dates in Django?
问题描述
使用Django和Python 3.7.我正在尝试编写查询以给我两个日期之间的差异的平均值.我的模型中有两个字段,均为"DateTimeField",我尝试像这样计算平均差
Using Django and Python 3.7. I'm tryhing to write a query to give me the average of the difference between two dates. I have two fields in my model, both "DateTimeField"s, and I try to calculate the average difference like so
everything_avg = Article.objects.aggregate(
avg_score=Avg(F('removed_date') - F('created_on'), output_field=models.DateTimeField())
).filter(removed_date__isnull=False)
return everything_avg
但是运行以上命令时我最终收到此错误
but I end up getting this error when running the above
AttributeError: 'dict' object has no attribute 'filter'
什么是获得我的平均值的正确方法?
What's the right way to get my average?
推荐答案
如文档所述:
aggregate()是QuerySet的终端子句,该子句在调用时返回名称-值对的字典. * >
aggregate方法返回一个字典,因此您需要先对其进行过滤.因此,如果您按照以下方式更改代码,则会得到结果:
aggregate method returns a dictionary, thus you need to make your filtering before it. Thus if you alter your code as following you would get your result:
everything_avg = Article.objects.filter(removed_date__isnull=False)\
.aggregate(
avg_score=Avg(
F('removed_date') - F('created_on'),
output_field=models.DateTimeField()
)
)
return everything_avg
这篇关于如何计算Django中两个日期之间的平均差?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!