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]
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.
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.
Do Django models support multiple-column primary keys? ¶ No. Only single-column primary keys are supported.
TimeStampedModel - An Abstract Base Class model that provides self-managed created and modified fields.
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With