0

i am trying to add a search bar on my listview page. it will get all the post items first time, and if a query put in search box, and submitted, it will return a filtered queryset. it renders fine, but only has problem with pagination. for non-filtered queryset, the next page will get the next two posts without any problem, but for filtered queryset, i can see the queryset is correctly reflected by see less pages, but the next page gets me the second page of non-filtered queryset not the filtered queryset. Can anyone give me some pointers on what i am doing wrong here. Thanks

My template looks like this:

{% block content %}
  .....
 <form action="" method="get">
            <input type="text" name='q'>
            <input type="submit" value="Search">
     </form>


    {% for post in object_list %}
    ....
    {% endfor %}


    {% if is_paginated %}
            <div class="pagination">
                <span class="page-links">
                    {% if page_obj.has_previous %}
                        <a href="?page={{ page_obj.previous_page_number }}"><<</a>
                    {% endif %}
                    <span class="page-current">
                        Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
                    </span>
                    {% if page_obj.has_next %}
                        <a href="?page={{ page_obj.next_page_number }}">>></a>
                    {% endif %}
                </span>
            </div>
{% endif %}

I have a listview like below.

class Postlist(ListView):
model=post    
paginate_by = 2
query_string = ''

def get_queryset(self):


    if ('q' in self.request.GET) and self.request.GET['q'].strip():
       query_string = self.request.GET['q']
       entry_query = get_query(query_string, ['title', 'body',]) ## call get_query() function
       queryset = post.objects.filter(entry_query).order_by('-created')

    else:
       queryset=post.objects.all().order_by('-created')

    return queryset

def get_context_data(self):
    context = super(ListView, self).get_context_data(**kwargs)
    context['q'] = query_string
    ## do sth here to pre-populate the input text box
    return context
1
  • actually i figure out what the problem is. because get_query() is lazy. next page function will actually initiate another query to the database to fetch next two items, and because by the time it queries, my 'q' doesnt have any search terms, so the logic goes to "else" section to fetch all posts. I think overriding get_context_data() to preserve the search term during each postback will solve the problem.
    – John
    Oct 25, 2013 at 1:18

1 Answer 1

0

Let me close this. Two options: using hidden field to save the user search terms, and get this to filter off queryset on each request; or using session. Here is the session code sample. The only drawback i could think of using session cache is it caches a whole queryset in memory, so it will kill the memory for high traffic website. Since i am using it for personal website, it doesnt hurt at all.

View file

class Postlist(ListView):
model=post
paginate_by = 2

def get_queryset(self):
    query_string = ''
    if ('search' in self.request.GET) and self.request.GET['search'].strip():
       query_string = self.request.GET['search']
       entry_query = get_query(query_string, ['title', 'body',]) ## call get_query to clean search terms
       queryset = post.objects.filter(entry_query).order_by('-created')
       self.request.session['searchset']=queryset

    else:
       if self.request.session.get('searchset') and ('page' in self.request.GET):
           queryset=self.request.session['searchset']
       else:
           queryset=post.objects.all().order_by('-created')
           if self.request.session.get('searchset'):
             del self.request.session['searchset']
    return queryset

form file

from django import forms

class SearchForm(forms.Form): search = forms.CharField(max_length=30)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.