Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting next and previous objects in Django

I'm trying to get the next and previous objects of a comic book issue. Simply changing the id number or filtering through date added is not going to work because I don't add the issues sequentially.

This is how my views are setup and it WORKS for prev_issue and does return the previous object, but it returns the last object for next_issue and I do not know why.

def issue(request, issue_id):     issue = get_object_or_404(Issue, pk=issue_id)     title = Title.objects.filter(issue=issue)     prev_issue = Issue.objects.filter(title=title).filter(number__lt=issue.number)[0:1]     next_issue = Issue.objects.filter(title=title).filter(number__gt=issue.number)[0:1] 
like image 938
AAA Avatar asked May 16 '11 18:05

AAA


People also ask

What does .all do in Django?

Definition of the all() manager method: all() Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result.

What does .values do in Django?

values() Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.

Can Django model have two primary keys?

Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.

What is timestamped model in Django?

TimeStampedModel - An Abstract Base Class model that provides self-managed created and modified fields.


2 Answers

Add an order_by clause to ensure it orders by number.

next_issue = Issue.objects.filter(title=title, number__gt=issue.number).order_by('number').first() 
like image 77
Steve Mayne Avatar answered Oct 03 '22 20:10

Steve Mayne


I know this is a bit late, but for anyone else, django does have a nicer way to do this, see https://docs.djangoproject.com/en/1.7/ref/models/instances/#django.db.models.Model.get_previous_by_FOO

So the answer here would be something something like

next_issue = Issue.get_next_by_number(issue, title=title) 

Django managers to do that with a bit of meta class cleaverness.

like image 27
Michael Buckley Avatar answered Oct 03 '22 19:10

Michael Buckley