Let's say I have the following:
MY_CHOICES = ( (1, "Choice 1"), (2, "Choice 2"), (3, "Choice 3"), ) class MyModel(models.Model): name = models.CharField(max_length=64, ) category = models.CharField(max_length=4, choices=MY_CHOICES)
Now, what I'd like to do is group by category and get the number of instances for each group. For instance, I'd like to get a result like this:
Choice 1: 31 Instances Choice 2: 4 Instances Choice 3: 2 Intances
This can be done with the following query:
group_by_category = MyModel.objects.values('category').distinct().annotate(count=Count('category')) The above works however because the values() will return a ValueQuerySet (which contains dicts instead of MyModel instances). So I am not able to use "get_category_display" to output "Choice 1", "Choice 2" etc, but I can only print the numbers.
Is there a DRY way to be able to use the get_category_display method ?
I know that I can add the display value myself using a for loop to modify each dict (if category=='1' then its display value is "Choice 1" etc) however I don't feel that's DRY enough.