How do I calculate the average difference between two dates in Django?

给你一囗甜甜゛ 提交于 2021-01-28 12:22:37

问题


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?


回答1:


As the documentation says:

aggregate() is a terminal clause for a QuerySet that, when invoked, returns a dictionary of name-value pairs. *

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


来源:https://stackoverflow.com/questions/55635951/how-do-i-calculate-the-average-difference-between-two-dates-in-django

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