0

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 dictwith 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?

Mormoran
  • 751
  • 13
  • 34
  • But that isn't what annotate gives you. It gives you a list of dictionaries, each one containing 'fault_type__name' and 'count'. – Daniel Roseman Nov 01 '19 at 18:40
  • What isn't it gives me? The output I want, or the output I'm getting? Is it possible to extract the output I want through a queryset? – Mormoran Nov 02 '19 at 00:31
  • The output you show here is not the output of annotate. The code you have shown here would give you the output I described. – Daniel Roseman Nov 02 '19 at 08:49

0 Answers0