Django queryset注释,charfield带选项并尝试获取显示值

2024-09-29 18:39:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我的模型的相关部分:

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)

我正在尝试运行聚合命令。它就像这样工作得很好:

^{pr2}$

但是,问题是注释label返回“APP”、“WEB”、“DASH”,而不是实际的显示值。我知道我可以正常使用get_FOO_display(),但如何将显示值拉入注释调用?我正在寻找我的source字段的显示值。谢谢!在


Tags: 模型webtrueappsourcemodelmodelsmobile
1条回答
网友
1楼 · 发布于 2024-09-29 18:39:46
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())

你能试试上面的代码片段吗,希望对你有帮助

相关问题 更多 >

    热门问题