python中的动态变量名 [英] Dynamic variable name in python

查看:121
本文介绍了python中的动态变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用一个字段名称过滤器的查询,我不会在运行时间之前知道...不知道如何构造变量名称...或者也许我很累。

  field_name = funct()
locations = Locations.objects.filter(field_name__lte = arg1)
/ pre>

如果funct()返回名称等于

  locations = Locations.objects.filter(name__lte = arg1)

不知道该怎么做

解决方案

您可以创建一个字典,设置参数并将其传递给将字典解包为关键词参数

  field_name = funct()
params = {field_name +'__lte':arg1,#field_name应该还包含字符串
'some_other_field_name':arg2}

位置=位置.objects.filter(** params)

#与(假定为field_name ='some_name')相同:
#Locations.objects.filter(some_name__lte = arg1,some_other_field_name = arg2)


I'd like to call a query with a field name filter that I wont know before run time... Not sure how to construct the variable name ...Or maybe I am tired.

field_name = funct()
locations = Locations.objects.filter(field_name__lte=arg1)

where if funct() returns name would equal to

locations = Locations.objects.filter(name__lte=arg1)

Not sure how to do that ...

解决方案

You can create a dictionary, set the parameters and pass this to the function by unpacking the dictionary as keyword arguments:

field_name = funct()
params = {field_name + '__lte': arg1,       # field_name should still contain string
          'some_other_field_name': arg2}

locations = Locations.objects.filter(**params)

# is the same as (assuming field_name = 'some_name'):
# Locations.objects.filter(some_name__lte=arg1, some_other_field_name=arg2)

这篇关于python中的动态变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆