简体   繁体   English

Django queryset批注,具有选择项并尝试获取显示值的charfield

[英]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. 但是,问题是注释label返回的是“ APP”,“ WEB”,“ DASH”,而不是实际的显示值。 I know I can use get_FOO_display() normally, but how can I pull in the display value into my annotation call? 我知道我可以正常使用get_FOO_display() ,但是如何将显示值插入注释调用中? I am looking to get the display values of my source field. 我正在寻找我的source字段的显示值。 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 您可以尝试上述代码片段,希望对您有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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