queryset注释中的动态字段名称

问题描述 投票:1回答:1

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

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

所以在这种情况下,无论变量指标带有什么值,输出看起来都像:

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

我需要一个键名等于公制变量的输出(如果公制=='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个回答
3
投票
# 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)
© www.soinside.com 2019 - 2024. All rights reserved.