Here is my Django model:
class MyModel(models.Model):
a = IntegerField()
b = DateTimeField()
Here is the QuerySet I execute on this model to find the count, min, max and average b
s for each value of a
:
>>> from django.db.models import Count, Max, Min, Avg
>>> MyModel.objects.extra(
... select={'avg': 'AVG(UNIX_TIMESTAMP(b))'}
... ).values('a').annotate(
... count=Count('b'),
... min=Min('b'),
... max=Max('b'),
... )
Here is the result of the QuerySet above:
[
{'a': 1, 'count': 5, 'min': datetime.datetime(2015, 2, 26, 1, 8, 21, tzinfo=<UTC>), 'max': datetime.datetime(2015, 2, 26, 1, 8, 22, tzinfo=<UTC>)},
{'a': 2, 'count': 2, 'min': datetime.datetime(2015, 2, 26, 1, 8, 21, tzinfo=<UTC>), 'max': datetime.datetime(2015, 2, 26, 1, 8, 22, tzinfo=<UTC>)}
]
As you can see, the results of the QuerySet do not include the average field that I calculated. How can I get that in there? I have tried many different permutations. But if I can get the avg
field in there, then it seems to screw up the grouping by a
.
Instead of using the Django ORM, you could use a raw sql query.
This will give you something like:
Otherwise, the closest thing I could get using Django's ORM would be to abandon the UNIX_TIMESTAMP conversion in the extra clause:
Unfortunately, this will give you the average as a float.
]
You can try using something like
to convert it back to a datetime object, though this will be an approximation, so I recommend using raw sql instead.