我正在尝试动态构建Q对象。这是我的代码:
class StudentiRicerche(ListAPIView):
serializer_class = StudentiLista
def get_queryset(self):
query_params = self.request.query_params
q_objects = Q()
for k, v in query_params.items():
param = '{0}__icontains={1}'.format(k, v) # k and v are dynamic values
q_objects &= Q(param)
queryset = Studenti.objects.filter(q_objects) # Here i get an error
return queryset
使用此代码,我在使用过滤器
的行上获得了ValueError我还试图以这种方式直接使用Q对象的Q对象列表:
class StudentiRicerche(ListAPIView):
serializer_class = StudentiLista
def get_queryset(self):
query_params = self.request.query_params
q_list = []
for k, v in query_params.items():
param = '{0}__icontains={1}'.format(k, v)
q_list.append(Q(param)) # Q with 'and' condition
queryset = Studenti.objects.filter(*q_list) # here I get an error also
return queryset
但是我在这里又犯了同样的错误!有什么想法??
答案 0 :(得分:1)
简化。你不需要使用Q:
class StudentiRicerche(ListAPIView):
serializer_class = StudentiLista
def get_queryset(self):
query_params = self.request.query_params
queryset = Studenti.objects.filter(**{'{}__icontains'.format(k):v for k,v in query_params.items() })
return queryset
说明:
.filter
和Q()
的参数是字典,而不是列表.filter
和Q()
使用命名参数,例如:.filter(name__icontains='Ivan', email__icontains='mail.com')
.filter(**{'name__icontains':'Ivan', 'email__icontains': 'mail.com')
.filter(**{'{}__icontains'.format(k):v for k,v in query_params.items() })
Q()
,则必须使用字典:Q(**{'{}__icontains'.format(k):v for k,v in query_params.items() })
另外
.filter(is_active__isnull=False, **{'{}__icontains'.format(k):v for k,v in query_params.items() })