如何在查询中创建泛型变量

时间:2013-07-03 11:17:06

标签: django

我有这个问题:

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)。

1 个答案:

答案 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)