在django中使用Q Expression时查询后没有搜索结果

时间:2018-04-25 06:44:52

标签: python django python-3.x django-rest-framework

我有以下基于类的视图我已经实现了自定义查询功能但是当我尝试搜索时我没有得到结果。我在数据库中提供了有关员工详细信息的数据,但没有结果。这就是我的Q滤镜的样子。

class PayslipSearch(ListAPIView):
# queryset = Payslip.obejcts.all()
serializer_class = PayslipDetailSerializer
filter_backends = [SearchFilter]
search_fields = ['employee__user__first_name',
                 'employee__user__last_name',
                 'basic_salary__salary_value',
                 # 'payment_mode',
                 # 'payslip_no',
                 # 'month_ending',
                 # 'deductions',
                 # 'allowances'
                 ]

def get_queryset(self, *args, **kwargs):
    queryset_list = Payslip.objects.all()
    # call GETs get to get your values
    query = self.request.GET.get("q")
    print(query)

    if query:
        queryset_list = Payslip.objects.filter(
            Q(employee__user__first_name__icontains=query) |
            Q(employee__user__last_name__icontains=query) |
            Q(basic_salary__salary_value__icontains=query)
            # Q(payment_mode__icontains=query) |
            # Q(payslip_no__icontains=query) |
            # Q(month_ending__icontains=query) |
            # Q(allowances__icontains=query) |
            # Q(deductions__icontains=query)
        ).distinct()

    return queryset_list

1 个答案:

答案 0 :(得分:0)

我如何实施搜索:

class EmployeeSearch(APIView):

    # custom dictionary

    def get(self, request, format=None):
        query = self.request.query_params["q"]

        if query:
            queryset_list = Employee.objects.filter(
                Q(user__first_name__icontains=query)
            ).values(
                'user__id', 'department', 'hr_number', 'salaries__salary_value',
                'tax_id_number', 'job_group', 'job_group_id',
                'identification_number',
                'joining_date', 'payslips',
                'user__last_name', 'user__first_name', 'user__email'
            )

        return Response(data=queryset_list, status=status.HTTP_200_OK)