Searching for Records

Posted by 47 on Stack Overflow See other posts from Stack Overflow or by 47
Published on 2010-04-13T17:39:33Z Indexed on 2010/04/13 17:43 UTC
Read the original article Hit count: 414

Filed under:
|

I've come up with a simple search view to search for records in my app. The user just enters all parameters in the search box then all this is matched against the database, then results are returned. One of these fields is the phone number....now in the database it's stored in the format XXX-XXX-XXX. A search, for example, for "765-4321" pull up only "416-765-4321...however I want it to return both "416-765-4321" and "4167654321"

My view is as below:

def search(request, page_by=None):    
   query = request.GET.get('q', '')
   if query:
      term_list = query.split(' ')
      q = Q(first_name__icontains=term_list[0]) | 
          Q(last_name__icontains=term_list[0]) | 
          Q(email_address__icontains=term_list[0]) | 
          Q(phone_number__icontains=term_list[0])
      for term in term_list[1:]:
          q.add((Q(first_name__icontains=term) | 
                 Q(last_name__icontains=term) | 
                 Q(email_address__icontains=term) | 
                 Q(phone_number__icontains=term)), q.connector)
      results = Customer.objects.filter(q).distinct()
      all = results.count()
  else:
    results = []

  if 'page_by' in request.GET:
    page_by = int(request.REQUEST['page_by'])
  else:
    page_by = 50

  return render_to_response('customers/customers-all.html', 
                             locals(), context_instance=RequestContext(request))

© Stack Overflow or respective owner

Related posts about django

Related posts about search