查询集注释中的动态字段名称
Dynamic field name in queryset annotation
我需要用传入的变量值重命名输出字段名称。有一个函数:
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"}
我需要一个键名等于度量变量的输出(如果度量 == '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' 列。
那么有什么方法可以将字段名称作为变量传递吗?
# 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)
我需要用传入的变量值重命名输出字段名称。有一个函数:
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"}
我需要一个键名等于度量变量的输出(如果度量 == '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' 列。 那么有什么方法可以将字段名称作为变量传递吗?
# 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)