Oli
Oli

Reputation: 239988

Find previous and next items in a Django queryset, given an item

So I'm building a blog in Django but I'm having a brain freeze.

I'm on a BlogPost detail view and I need to work out the previous and next posts so I can offer them as navigation options after the post body. For the sake of this question, I have two things:

I don't have an index of the blog post in the query, nor does it sound right to scan the whole queryset for my initial blog post. Is there an intelligent and inexpensive way of getting objects from either side of a given one (if you don't know where it is to begin with)?

Upvotes: 2

Views: 748

Answers (1)

Hedde van der Heide
Hedde van der Heide

Reputation: 22459

Model.get_next_by_FOO  # get_previous_by_FOO

Slightly underexposed by the Django documentation, but useful:

For every DateField and DateTimeField that does not have null=True, the object will have get_next_by_FOO() and get_previous_by_FOO() methods, where FOO is the name of the field. This returns the next and previous object with respect to the date field, raising a DoesNotExist exception when appropriate.

Upvotes: 3

Related Questions