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
.