I have 2 models:
class FaultType(models.Model):
name = models.CharField(max_length=255, blank=False, default='')
visible = models.BooleanField(default=True)
And
class RunFault(models.Model):
run = models.ForeignKey(Run, on_delete=models.CASCADE)
fault_type = models.ForeignKey(FaultType, on_delete=models.CASCADE)
note = models.CharField(max_length=100, blank=True, default='')
I need to group all instances of RunFault by FaultType, and count them.
Preferably obtain a dict
with structure (example):
faults = {
"some_fault" = 7,
"foo_fault" = 4,
"bar_fault" = 13
}
(Where "blabla_fault" is FaultType.name)
Basically I need the dict
key to be the FaultType.name
and the value to be the count.
Right now I'm querying the DB like so:
faults = RunFault.objects.values('fault_type__name').order_by('fault_type').annotate(count=Count('fault_type__name'))
But that returns a list
of dicts
like so:
faults = [
{"fault_type__name": "some_fault"},
{"count": 7},
{"fault_type__name": "foo_fault"},
{"count": 4},
{"fault_type__name": "bar_fault"},
{"count": 13}
]
Where one dict
has key fault_type__name
and value FaultType.name
and another dict
has key count
with the value being the actual count.
Hard to use them like that as I can't know which count belongs to which FaultType
!
Is that the intended behaviour of .annotate(count=Count('some_key'))
?
Or am I doing the wrong query?