我想从多个模型中获取queryset。我正在尝试使用和条件实现多重搜索。views.py,
def list(self, request, *args, **kwargs):
search_query = self.request.query_params.get('search')
split_query = search_query.split()
employment = None
employee1 = []
employment1 = []
for query in split_query:
print("hi", query)
# query = self.request.query_params.get('search')
employee = PositionFulfillment.objects.filter(
Q(employment__employee__code__icontains=query) |
Q(employment__employee__person__name__icontains=query) |
Q(employment__employee__person__surname__icontains=query)
)
# emp = list(chain(employee))
employee1.append(employee)
print("employee", employee1)
active_employee = PositionFulfillment.objects.filter(primary_flag=True, thru_date=None)
if active_employee:
employment = active_employee.filter(
Q(position__position_type__name__icontains=query) |
Q(employment__organization__name__icontains=query) |
Q(employment__status__status__employment_status__icontains=query)
)
employment1.append(employment)
all_results = list(chain(map(lambda x: x, employee1), map(lambda y: y, employment1)))
# all_results = list(chain(employee, employment))
print("all_results", all_results)
serializer = EmployeeSearchSerializer(all_results)
return Response(serializer.data, status=status.HTTP_200_OK)
我得到的输出如下,
all_results,
[<QuerySet [<PositionFulfillment: 27>, <PositionFulfillment: 29>, <PositionFulfillment: 30>]>, <QuerySet []>, <QuerySet []>, <QuerySet [<PositionFulfillment: 28>]>]
Expected output,
[<PositionFulfillment: 27>, <PositionFulfillment: 29>, <PositionFulfillment: 30>]> ,<QuerySet [<PositionFulfillment: 28>]>]
我怎样才能做到这一点???
您可以向查询添加条件,而不是创建新的查询:
def list(self, request, *args, **kwargs):
search_query = self.request.query_params.get('search')
split_query = search_query.split()
q = None # this is filter
for query in split_query:
print("hi", query)
if q is None:
q = Q(employment__employee__code__icontains=query)
else:
q.add(Q(employment__employee__code__icontains=query), Q.OR)
q.add(Q(employment__employee__person__name__icontains=query), Q.OR)
q.add(Q(employment__employee__person__surname__icontains=query), Q.OR)
# same for active_employee
# make only one query based on all conditions in q
all_results = PositionFulfillment.objects.filter(q)
print("all_results", all_results)
serializer = EmployeeSearchSerializer(all_results)
return Response(serializer.data, status=status.HTTP_200_OK)