Saturday, 15 September 2012

python - How to do complex query like this -



python - How to do complex query like this -

i have next , get_queryset methods in customerslistview class:

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') homecoming 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), ] homecoming customer.objects.filter(reduce(operator.and_, query_list))

user can submit info in next ways:

1: if user submits empty form entries of client model should returned.

2: if user submits info in 1 field info should filtered according field.

3: if user submits info in more 1 field query should filter info according both field mean(and).

note: request.get.get() homecoming u'' empty form fields. , id should integer searching client model id not unicode string u''.

for illustration :

>>> customer.objects.filter(q(id=none) , q(first_name__contains='secon') , q (last_name__contains='')) [<customer: vaibhav kumar jain >, <customer: sec client sec client sec client >]

but want results corresponding q(first_name__contains='secon') lookup

<customer: sec client sec client sec client > not

[<customer: vaibhav kumar jain >, <customer: sec client sec client sec client >]

you can keyword arguments , filtering:

def get_queryset(self): # filters_map keys must match 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) key, value in filters_map.iteritems() if value) homecoming customer.objects.filter(**query)

a bit more keyword arguments.

ps: think makes more sense filter queryset in get_queryset method.

python django django-models

No comments:

Post a Comment