要继续@iuysal 答案:
为了使其通用,您还需要将密钥作为参数传递,为此您需要传递字典,这就是我的做法:
像这样创建你的字典:
filters = {'filter1': 'value1', 'filter2__startswith': 'valu', ...}
然后将其传递给您的项目过滤器,如下所示:
Item.objects.filter(*[Q(**{k: v}) for k, v in filters.items() if v], filter3='value3')
我拥有的第一个版本不那么神秘:
def _filter(filters):
filters = []
for k, v in n.items():
if v:
filters.append(Q(**{k: v}))
return filters
filters = _filter({'name': name})
return Item.objects.filter(*filters)
开箱说明:我们想给Q (queries)
as args
to objects.filter
as args 而我们想给kwargs
toQ()
我现在正在生产中(我将只修改过滤器名称,因为它很敏感):
def get_queryset(self):
filter1 = self.request.GET.get('filter1 ', '')
filter2__startswith = self.request.GET.get('filter2_prefix ', '')
def filters_to_Qs(filters):
return [Q(**{k: v}) for k, v in filters.items() if v]
filters = {'filter1': filter1 ,
'filter2__startswith': filter2__startswith }
return Order.objects.filter(*filters_to_Qs(filters))