简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM