Eag*_*One 1 django optimization
在Django中,我使用如下的分页符:
来自django.core.paginator导入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)
Run Code Online (Sandbox Code Playgroud)
在s.search()函数中,我对postgres db进行查询.
事实证明,即使我每页显示10个项目,查询也不受限制.
我试图用a限制查询Annonce.objects.filter(name="huhu")[:10]并自己指定计数.但是如果我这样做,分页器就不起作用了.
有没有办法优化这个?
Cal*_*eng 10
使用此示例https://docs.djangoproject.com/en/dev/topics/pagination/#using-paginator-in-a-view作为编写适当使用django Paginator的视图函数的指南.
请注意,在示例代码段中 -
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.
Run Code Online (Sandbox Code Playgroud)
contact_list是一个尚未实际评估过的已分配查询集.paginator = Paginator(contact_list, 25)对a 的赋值Paginator instance是懒惰的,并且在必须之前不会真正执行.
page = request.GET.get('page')?page=2从您的网址获取额外的GET变量(例如).http://localhost:8000/my/listing?page=2当我们尝试检索应该出现在您的列表页面上的25个对象时,该网址实际上就像是第2页.
这是执行数据库的实际查询的地方: -
try:
contacts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
contacts = paginator.page(1)
Run Code Online (Sandbox Code Playgroud)
在contacts = paginator.page(page)执行查询的数据库中检索只有一组有限的基础上赋予它的页面数量的对象和我们想要每页的"25"对象的条件.
| 归档时间: |
|
| 查看次数: |
4836 次 |
| 最近记录: |