如何做这样的复杂查询

时间:2014-10-04 07:33:07

标签: python django django-models

我的CustomersListView类中有以下get和get_queryset方法:

def get(self, request, *args, **kwargs):
    """
    :param request:
    :param args:
    :param kwargs:
    :return:
    """


    self.id = request.GET.get('id')
    self.f_name = request.GET.get('f_name')
    self.m_name = request.GET.get('m_name')
    self.l_name = request.GET.get('l_name')
    self.r_name = request.GET.get('r_name')
    self.p_no = request.GET.get('p_no')
    self.gender = request.GET.get('gender')


    return super(CustomersListView, self).get(request, *args, **kwargs)

def get_queryset(self):
    """
    :return:
    """

    query_list = [Q(id=self.id), Q(first_name__contains=self.f_name), Q(middle_name__contains=self.m_name),
                  Q(last_name__contains=self.l_name), Q(relative_name__contains=self.r_name),
                  Q(phone_no_1__contains=self.p_no), Q(phone_no_2__contains=self.p_no), Q(gender=self.gender),
                  ]

    return Customer.objects.filter(reduce(operator.and_, query_list))

用户可以通过以下方式提交数据:

1:如果用户提交空表单,则应返回Customer模型的所有条目。

2:如果用户在任何一个字段中提交数据,则应根据该字段过滤数据。

3:如果用户在多个字段中提交数据,则查询应根据我的意思(和)字段过滤数据。

注意:request.GET.get()将为空表单字段返回u''id应为integerid而不是unicode string u''来搜索客户模型。

例如:

>>> Customer.objects.filter(Q(id=None) and Q(first_name__contains='Secon') and Q (last_name__contains=''))

[<Customer: vaibhav kumar jain >, <Customer: second customer second customer second customer >]

但我希望结果只对应Q(first_name__contains='Secon')查找

<Customer: second customer second customer second customer >不是

[<Customer: vaibhav kumar jain >, <Customer: second customer second customer second customer >]

1 个答案:

答案 0 :(得分:1)

您可以使用关键字参数和一些过滤来执行此操作:

def get_queryset(self):
    # filters_map keys must match your queries
    filters_map = {
        'id': self.request.GET.get('id'),
        'first_name__icontains': self.request.GET.get('f_name'),
        'middle_name__icontains': self.request.GET.get('m_name'),
        'last_name__icontains': self.request.GET.get('l_name'),
        'relative_name__icontains': self.request.GET.get('r_name'),
        'phone_no_1__contains': self.request.GET.get('p_no'),
        'phone_no_2__contains': self.request.GET.get('p_no'),
        'gender': self.request.GET.get('gender')
    }
    # leave out empty strings
    query = dict((key, value) for key, value in filters_map.iteritems() if value)

    return Customer.objects.filter(**query)

更多关于keyword arguments

PS:我认为在get_queryset方法中过滤查询集更有意义。