计算 Django 的平均年龄
我需要找出项目的平均年龄(按各种标准分组,但这似乎不是问题)。但是,我无法找到如何使用 Django(在 MySQL 之上)有效地在 DateTimeField 上创建聚合。
纯 Item.objects.all.aggregate(Avg('created'))
似乎会产生绝对虚假的值(例如 20081988007238.133)并使用 Item.objects.all.extra(... )
我还没有找到如何聚合的方法。
当然,我可以手动创建 SQL 查询(类似于 SELECT AVG(UNIX_TIMESTAMP(created)) FROM items_item),但我宁愿避免在应用程序中使用 MySQL 特定代码。
仅供参考,我用于测试的示例模型:
class Item(models.Model):
name = models.CharField(max_length = 255)
created = models.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).
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为没有其他方法可以使用
extra
方法。它应该看起来像这样(未经测试):问题是,您必须先将日期转换为 UNIX 时间戳。否则你无法计算平均值。平均字符串确实会产生垃圾。
I think there is no other way as using the
extra
method. It should look like this then (not tested):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.