implementing next and previous of the object

127 views
Skip to first unread message

haibin

unread,
Jul 28, 2010, 12:41:50 AM7/28/10
to Django users
Hi all,

Need help, advice on how the have a next and previous link on a object
detail page. For example fomr a object list page a user chose an
object, and in the object page instead of going back to the list to
view other object the user just click either next or previous.

Any idea how to implement it?

Thanks,
James

Sævar Öfjörð

unread,
Jul 28, 2010, 8:03:09 AM7/28/10
to Django users
It's probably best to do this in a custom Manager.
This code is based on this answer: http://markmail.org/message/kwwuskco4gilej2w

You get the idea

class GetPrevNextManager(models.Manager):
def get_next_by_id(self, object):
qs = self.filter(id__gt=object.id)
if qs.count() > 0:
return qs.order_by('id')[0]
# empty queryset
return qs

def get_prev_by_id(self, object):
qs = self.filter(id__lt=object.d)
if qs.count() > 0:
return qs.order_by('-id')[0]
# empty queryset
return qs

More information about managers: http://docs.djangoproject.com/en/dev/topics/db/managers/

- Sævar
Reply all
Reply to author
Forward
0 new messages