簡體   English   中英

Django queryset批注,具有選擇項並嘗試獲取顯示值的charfield

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

我模型的相關部分:

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)

我正在嘗試運行聚合命令。 它像這樣正常工作:

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

但是,問題是注釋label返回的是“ APP”,“ WEB”,“ DASH”,而不是實際的顯示值。 我知道我可以正常使用get_FOO_display() ,但是如何將顯示值插入注釋調用中? 我正在尋找我的source字段的顯示值。 謝謝!

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())

您可以嘗試上述代碼片段,希望對您有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM