I will guide you to create simple search using Django 1.3 queryset and with pagination. Because lack of documentation, I hope this will help you figure out how to create search engine in Django 1.3. I will create search page with GET method. So, you should see your query parameters in URL. Here are to do.
urls.py
1 | url(r’^search/$’, ‘search’, name=’search’), |
views.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | def search(request): """Making search query from given keyword and pagination pages if any.""" if request.method == ‘GET’: # Defining query set set_query = None query_build = None # Deleting page params from GET request params = request.GET.copy() if ‘page’ in params: del(params[‘page’]) for field_name in params : value = request.GET.get(‘%s’ % field_name) if value: # Set Q objects query_build = Q(**{"%s__exact" % field_name: value }) if set_query is None: set_query = query_build else: # Merge new Q objects with previous set_query = set_query & query_build if set_query: # Searching with Q SearchQuerySet business_result_plan = Business.objects.filter(set_query) paginator = Paginator(business_result, 1) try: page = int(request.GET.get(‘page’, ‘1’)) except ValueError: page = 1 try: paging = paginator.page(page) except (EmptyPage, InvalidPage): paging = paginator.page(paginator.num_pages) # Send GET param into pagination path = params.urlencode() return render_to_response(‘business/index.html’, {‘business’: paging, ‘path’: path, ‘query’: params}) |
In templates, search.html :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | {% for data in business.object_list %} {{ data.name }} {{ data.card }} {% endfor %} <div> {% if path %} <span> {% if business.has_previous %} <a href="?{{ path }}&page={{ business.previous_page_number }}">previous</a> {% endif %} {% for num in business.paginator.page_range %} {% ifequal num business.number %} <span class="current page">{{ num }}</span> {% else %} <a href="?{{ path }}&page={{ num }}"> {{ num }}</a> {% endifequal %} {% endfor %} {% if business.has_next %} <a href="?{{ path }}&page={{ business.next_page_number }}"> Next </a> {% endif %} </span> {% else %} <span> {% if business.has_previous %} <a href="?page={{ business.previous_page_number }}">previous</a> {% endif %} {% for num in business.paginator.page_range %} {% ifequal num business.number %} <span class="current page">{{ num }}</span> {% else %} <a href="?page={{ num }}"> {{ num }}</a> {% endifequal %} {% endfor %} {% if business.has_next %} <a href="?page={{ business.next_page_number }}"> Next </a> {% endif %} </span> {% endif %} </div> |
Now you have search page with solving page problem parameter in pagination. Also, you can use {{ query.value }} on your input forms. This also works for multiple search form.