[Answered ]-Next or previous item within an ordered, filtered queryset in Django

1👍

If you want the previous or next item based on a DateTimeField, you can work with .get_previous_by_fieldname(…) [Django-doc] or .get_next_by_fieldname(…) [Django-doc]. You thus can obtain the previous/next item for stuff with:

try:
    prev_stuff = stuff.get_previous_by_post_date()
except Stuff.DoesNotExist:
    prev_stuff = None

try:
    next_stuff = stuff.get_next_by_post_date()
except Stuff.DoesNotExist:
    next_stuff = None

Leave a comment