Barranka
Barranka

Reputation: 21047

Django: Show Choices "verbose" name when querying (and the choice is in a related model)

I'm attempting to write a view that shows a table with number of items per status.

A simplified view of my models is as follows:

from django.db import models

class Entity(models.Model):
    name = models.CharField(max_length=20)

class Status(models.Model):
    BAD = 0
    NICE = 1
    GREAT = 2
    STATUS_CHOICES = (
        (BAD, 'Bad'),
        (NICE, 'Nice'),
        (GREAT, 'Great')
    )
    entity = models.OneToOneField(Entity, on_delete=models.CASCADE, 
                                  related_name='status')
    status = models.IntegerField(choices=STATUS_CHOICES, db_index=True)

So, in my views.py file, I have a view like this:

from django.shortcuts import render
from django.db.models import Count

def my_summary(request):
    q = Entity.objects.values('status__status').annotate(n=Count('pk'))
    context = {'table_data':q}
    return render(request, 'my_app/summary_template.html', context)

The issue I'm facing is that, when I render the template, I only get the number of the status, and I need to show the Label of that status. So, instead of showing

 status | entities
 -------+---------
   0    | 3
   1    | 5
   2    | 9

I'd like to show:

 status  | entities
 --------+---------
   BAD   | 3
   NICE  | 5
   GREAT | 9

Is there a way to do it? Can anyone point me in the right direction?

Upvotes: 2

Views: 1652

Answers (1)

Tomas Walch
Tomas Walch

Reputation: 2305

Django auto-generates getters for the choice labels, in your case it will be get_status_display. See https://docs.djangoproject.com/en/2.0/ref/models/instances/#django.db.models.Model.get_FOO_display

Upvotes: 3

Related Questions