我認爲你描述它的方式可以正常工作,因爲在幕後我相信Django正在做的是使用SQL LIMIT
來簡單地讓數據庫完成清理什麼和多少數據的繁重工作回來。因爲數據庫針對這種類型的事情進行了優化,所以這可能是一種合理的方式。
關鍵可能會保持查詢相同,並且您已經證明您可以使用相同的視圖來執行此操作。該視圖可以簡單地具有改變分頁頁數的奇特方式。
你可以用這樣的url結束了......
# View all "landscape" items in gallery mode starting on page 3
http://www.example.com/gallery/landscape/multi/3
# View the 45th landscape item in singular mode
http://www.example.com/gallery/landscape/single/45
當模板被渲染,在分頁程序將提供has_next
和has_previous
方法,讓你知道,如果你可以使用渲染/下一鏈接。
這裏就是我想的看法,或者說沿着這些線路(這是完全未測試並註銷我的頭頂部)...
url(r'gallery/(?P<category>.+)/(?P<mode>.+)/(?P<offset>\d+)$', 'whatever.views.media_gallery'),
def media_gallery(request, category, mode, offset):
"""
Render a media gallery.
category = media item category filter
mode = (multi | single)
offset = The pagination offset in multi mode or the media ID in single mode
"""
if mode == 'multi':
per_page = 20 # or however many items per page
elif mode == 'single':
per_page = 1
else:
pass # handle this however
# Queryitems
raw_media_items = Media.objects.filter(category=category)
# Setup paginator
paginator = Paginator(raw_media_items, per_page)
try:
# in multi mode offset is the page offset
# in single mode offset is the media ID
page = int(offset)
except:
page = 1
try:
media_items = paginator.page(page)
except (EmptyPage, InvalidPage):
media_items = paginator.page(paginator.num_pages)
if len(paginated_items) == 1:
# Render single view
return render_to_response('gallery/gallery_view.html',
{ 'media_item':media_items[0], 'paginator':paginator },
context_instance=RequestContext(request))
else:
# Render gallery view
return render_to_response('gallery/gallery_view.html',
{ 'media_items':media_items, 'paginator':paginator },
context_instance=RequestContext(request))