问题
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