1

In Django, I use the paginator like the following:

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def myView(request):
    ...
    paginator = Paginator(Annonce.objects.filter(name="huhu"), 10)
    paginator._count = s.count()
    try:
        annonces = paginator.page(page)
    except PageNotAnInteger:
        annonces = paginator.page(1)
    except EmptyPage:
        annonces = paginator.page(paginator.num_pages)

In the s.search() function I do a query on my postgres db.

It turns out that even if I display 10 items per page, the query is not limited.

I tried to limit the query with a Annonce.objects.filter(name="huhu")[:10] and specifying the count myself. But the paginator doesn't work if I do so.

Is there a way to optimize this?

4

1 回答 1

11

Use this example https://docs.djangoproject.com/en/dev/topics/pagination/#using-paginator-in-a-view as your guide to writing a view function which uses django Paginator appropriately.

Notice that in the example code snippert -

def listing(request):
    contact_list = Contacts.objects.all()
    paginator = Paginator(contact_list, 25) # Show 25 contacts per page

    page = request.GET.get('page')  # <--- This is the key to your solution.

contact_list is an assigned queryset which has not actually been evaluated yet. The paginator = Paginator(contact_list, 25) assignment to a Paginator instance is lazy and doesn't really get executed until it has to.

page = request.GET.get('page') gets your extra GET variable ?page=2 (as an example) from your url. The url would actually look something like http://localhost:8000/my/listing?page=2 when we attempt to retrieve the 25 objects that should appear on your listing page, page 2.

This is where the actual query to your database gets executed:-

try:
    contacts = paginator.page(page)
except PageNotAnInteger:
    # If page is not an integer, deliver first page.
    contacts = paginator.page(1)

the contacts = paginator.page(page) executes a query to the database retrieving only a limited set of objects based on the page number given to it and on the condition that we want "25" objects per page.

于 2012-11-04T02:13:24.110 回答