Calculating average age in Django

蓝咒 提交于 2019-12-13 03:37:49

问题


I need to find out average age of items (groupped by various criteria, but it does not seem to be the issue). However I fail to find how to effectively create aggregation over DateTimeField using Django (on top of MySQL).

Pure Item.objects.all.aggregate(Avg('created')) seems to produce absolutely bogus values (eg. 20081988007238.133) and using Item.objects.all.extra(...) I have not found a way how to aggregate.

Of course I can manually create SQL query (something like SELECT AVG(UNIX_TIMESTAMP(created)) FROM items_item), but I'd prefer to avoid using MySQL specific code in the application.

Just for the reference, sample model I use for testing:

class Item(models.Model):
    name = models.CharField(max_length = 255)
    created = models.DateTimeField()

回答1:


I think there is no other way as using the extra method. It should look like this then (not tested):

Item.objects.extra('avg': 'AVG(UNIX_TIMESTAMP(created))'.values('avg')

The problem is, that you have to convert the date to a UNIX timestamp before. Otherwise you cannot calculate the average. An average of string will indeed produce garbage.



来源:https://stackoverflow.com/questions/2364952/calculating-average-age-in-django

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