2

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.

2
  • It could be better to have a second model for your categories instead of using choices. Jun 14, 2014 at 8:41
  • @RodrigoOlmo I am aware of that however I don't want to change my database schema right now.
    – Serafeim
    Jun 14, 2014 at 8:44

1 Answer 1

1
>>> dict(MY_CHOICES)[1]
"Choice 1"

Why distinct()? Does it do anything in this case?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.