【问题标题】:Dynamic field name in queryset annotation查询集注释中的动态字段名称
【发布时间】:2017-03-16 10:35:46
【问题描述】:

我需要用传入的变量值重命名输出字段名称。有一个功能:

def metric_data(request, test_id, metric):
    metric_name = metric
    data = ServerMonitoringData.objects. \
        filter(test_id=test_id). \
        annotate(timestamp=RawSQL("((data->>%s)::timestamp)", ('timestamp',))).\
        annotate(metric=RawSQL("((data->>%s)::numeric)", (metric,))). \
        values('timestamp', "metric")

所以在这种情况下,无论变量 metric 带有什么值,输出看起来都是这样的:

 {"timestamp": "0:31:02", "metric": "8.82414500398"}

我需要一个键名等于 metric 变量的输出(如果 metric == 'CPU_iowait'):

{"timestamp": "0:31:02", "CPU_iowait": "8.82414500398"}

尝试使用这样的东西:

    metric_name = metric
...
    annotate(metric_name=F('metric')).\
    values('timestamp', metric_name)

但当存在“metric_name”时,它会尝试查找“CPU_iowait”列。 那么有没有办法将字段名称作为变量传递?

【问题讨论】:

    标签: python django django-models django-orm


    【解决方案1】:
    # use dict to map the metric's name to a RawSQL query 
    # and pass it as keyword argument to `.annotate`.
    metric_mapping = {
        metric: RawSQL("((data->>%s)::numeric)", (metric,))
    }
    queryset.annotate(**metric_mapping)
    

    【讨论】:

    • 您的annotate 通话中有错字。
    猜你喜欢
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 2021-10-17
    • 2018-11-27
    • 2014-11-30
    • 1970-01-01
    • 2014-07-06
    • 2020-07-31
    相关资源
    最近更新 更多