我想用运行时间之前我不知道的字段名称过滤器调用查询...不确定如何构造变量名称......或者我可能累了。
field_name = funct()
locations = Locations.objects.filter(field_name__lte=arg1)
如果funct()返回name将等于
locations = Locations.objects.filter(name__lte=arg1)
不知道怎么做......
答案 0 :(得分:10)
您可以创建字典,设置参数并通过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)