简体   繁体   English

计算Django的平均年龄

[英]Calculating average age in Django

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). 但是我找不到如何使用Django(在MySQL之上)有效地在DateTimeField上创建聚合的方法。

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. Item.objects.all.aggregate(Avg('created'))似乎会产生绝对虚假的值(例如20081988007238.133),并且使用Item.objects.all.extra(...)我还没有找到一种方法来汇总。

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. 当然,我可以手动创建SQL查询(例如, SELECT AVG(UNIX_TIMESTAMP(created)) FROM items_item ),但我希望避免在应用程序中使用MySQL特定的代码。

Just for the reference, sample model I use for testing: 仅供参考,我用于测试的样本模型:

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

I think there is no other way as using the extra method. 我认为没有其他方法可以使用extra方法。 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. 问题是,您必须先将日期转换为UNIX时间戳。 Otherwise you cannot calculate the average. 否则,您将无法计算平均值。 An average of string will indeed produce garbage. 平均一个字符串确实会产生垃圾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM