Aggregate by multiple fieldsΒΆ
We have a model which describes incidents.
class Incident(Model):
id = models.BigAutoField(primary_key=True)
title = models.CharField(max_length=1024, blank=True, null=True)
description = models.TextField(blank=True, null=True)
severity = models.CharField(max_length=32, choices=shortcuts.get_enum_choices(IncidentSeverity))
status = models.CharField(max_length=32, choices=shortcuts.get_enum_choices(IncidentStatus))
We need to get the number of incidents for each distinct status, severity pair. Expressed in SQL this would look like:
SELECT status, severity, count(*) AS num_incidents
GROUP BY status, severity
Solution is to use the values() method to first group the objects from the query set and than use annotate() to aggreate.
>>> summary = Incident.values("status", "severity").annotate(num_incidents=Count("*"))
>>> summary
{'severity': 'critical', 'status': 'new', 'num_incidents': 1}
See values() method.