我正在尝试将字符串用作函数中的参数。这样的事情可能吗?
from django.contrib.auth.models import User
param_var = 'contains'
User.objects.filter(first_name__{param_var}='John')
# ideally, this should equate to:
User.objects.filter(first_name__contains='John')
答案 0 :(得分:3)
param_var = 'contains'
User.objects.filter(**{'first_name__%s'%param_var: 'John'})
虽然我真的很想知道这样做的智慧......我想你可能会重新发明sql注入......
我怀疑有更好的方法。你应该解释一下你想要完成的更多内容。
答案 1 :(得分:1)
<强>解决:强>
# Something like this...
qs = User.objects.all()
parameters = {
'name': {
'type': 'get',
'filter': [
'first_name__icontains',
'last_name__icontains',
# ...
],
},
# ...
}
for parameter, data in parameters.items():
if data['type'] == 'get':
value = request.GET.get(parameter, None)
elif data['type'] == 'getlist':
value = request.GET.getlist(parameter)
if value:
query = Q()
for f in data['filter']:
query = query | Q(**{ f : value })
qs = qs.filter(query)