Mic*_*unn 5 django django-models django-queryset
我有一个基于模型对象的页面,我想要链接到上一页和下一页.我不喜欢我当前的解决方案,因为它需要评估整个查询集(以获取ids列表),然后再需要两个get查询.当然有一些方法可以一次完成吗?
def get_prev_and_next_page(current_page):
ids = list(Page.objects.values_list("id", flat=True))
current_idx = ids.index(current_page.id)
prev_page = Page.objects.get(id=ids[current_idx-1])
try:
next_page = Page.objects.get(id=ids[current_idx+1])
except IndexError:
next_page = Page.objects.get(id=ids[0])
return (prev_page, next_page)
Run Code Online (Sandbox Code Playgroud)
排序顺序在模型中定义,因此不必在此处理,但请注意,您不能假设ID是顺序的.
听起来像Paginator设置为1的门槛会做得很好.
# Full query set...
pages = Page.objects.filter(column=somevalue)
p = Paginator(pages, 1)
# Where next page would be something like...
if p.has_next():
p.page(p.number+1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3867 次 |
| 最近记录: |