计算Django的平均年龄 [英] Calculating average age in Django
问题描述
我需要找出商品的平均年龄(按各种标准分组,但这似乎不是问题)。但是我找不到如何使用Django(在MySQL之上)有效地在DateTimeField上创建聚合的方法。
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).
纯 Item.objects.all.aggregate (Avg('created'))
似乎会产生绝对虚假的值(例如20081988007238.133)并使用 Item.objects.all.extra(...)
我还没有找到一种汇总方法。
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.
当然,我可以手动创建SQL查询(例如 SELECT AVG(UNIX_TIMESTAMP(创建))FROM items_item
),但我宁愿避免在应用程序中使用MySQL特定代码。
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()
推荐答案
我认为没有其他方法可以使用 extra
方法。然后应该看起来像这样(未经测试):
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')
问题是,您必须转换日期要早于UNIX时间戳记。否则,您将无法计算平均值。字符串的平均值确实会产生垃圾。
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.
这篇关于计算Django的平均年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!