Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next previous links from a query set / generic views

I have a quite simple query set and a related generic views:

f_detail = {
         'queryset': Foto.objects.all(),
         'template_name': 'foto_dettaglio.html',
         "template_object_name" : "foto",
       }

urlpatterns = patterns('',
# This very include
(r'^foto/(?P<object_id>\d+)/$', list_detail.object_detail, f_detail, ),
)

Just a template for generating a detail page of a photo: so there's no view.


Is there an easy way to have a link to previous | next element in the template without manualy coding a view ?

Somthing like a:

{% if foto.next_item %} 
  <a href="/path/foto/{{ foto.next_item.id_field }}/">Next</a> 
{% endif}
like image 792
eaman Avatar asked Feb 06 '10 21:02

eaman


1 Answers

class Foto(model):
  ...
  def get_next(self):
    next = Foto.objects.filter(id__gt=self.id)
    if next:
      return next.first()
    return False

  def get_prev(self):
    prev = Foto.objects.filter(id__lt=self.id).order_by('-id')
    if prev:
      return prev.first()
    return False

you can tweak these to your liking. i just looked at your question again... to make it easier than having the if statement, you could make the methods return the markup for the link to the next/prev if there is one, otherwise return nothing. then you'd just do foto.get_next etc. also remember that querysets are lazy so you're not actually getting tons of items in next/prev.

like image 148
Brandon Henry Avatar answered Oct 20 '22 05:10

Brandon Henry