我有这个问题:
search = request.GET['q']
Entries = Entry.objects.filter(Q(field1__icontains=search), Q(field2__icontains=search), Q(field3__icontains=search))
有一种优雅的方法可以让它更干净吗? (我的意思是像Q(var_field__icontains=search)
那样使用somthing,并且var_field
将从请求的帖子中重新获取,该帖子是其中一个值field1,field2,field3)。
答案 0 :(得分:0)
那么,这适合你吗?
search = request.GET['q']
fieldnames = ('field1', 'field2', 'field3')
filters = reduce(operator.and_,
(Q(**{'{}__icontains'.format(fieldname): search})
for fieldname in fieldnames))
Entries = Entry.objects.filter(filters)