capcom
capcom

Reputation: 525

Django queryset annotation, charfield with choices and trying to get the display value

The relevant bits of my model:

class AnalyticRecord(models.Model):

    APP = "APP"
    WEB = "WEB"
    DASH = "DASH"

    SOURCE_CHOICES = (
        (APP, "Mobile Application"),
        (WEB, "Website"),
        (DASH, "User Dashboard"))

    user = models.ForeignKey(User, blank=True, null=True)
    event = models.ForeignKey(Event)
    source = models.CharField(max_length=25, choices=SOURCE_CHOICES)

I am trying to run an aggregation command. It works just fine like this:

data = event.analyticrecord_set.all().values("source").\
    annotate(label=Concat("source", Value(None), output_field=CharField()))

However, the problem is the annotation label returns "APP", "WEB", "DASH" instead of the actual display value. I know I can use get_FOO_display() normally, but how can I pull in the display value into my annotation call? I am looking to get the display values of my source field. Thanks!

Upvotes: 2

Views: 3255

Answers (1)

pramod
pramod

Reputation: 1493

queryset = event.analyticrecord_set.all().values("source").\
    annotate(label=Concat("source", Value(None), output_field=CharField()))

for query in queryset:
    print(queryset.model(source=query['source']).get_source_display())

can you try above code snippet, hope this helps

Upvotes: 3

Related Questions