在 Django 中获取下一个和上一个对象 [英] Getting next and previous objects in Django

查看:32
本文介绍了在 Django 中获取下一个和上一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取漫画书问题的下一个和上一个对象.简单地更改 ID 号或过滤添加的日期是行不通的,因为我没有按顺序添加问题.

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.

这就是我的视图的设置方式,它适用于 prev_issue 并返回前一个对象,但它返回 next_issue 的最后一个对象,我不知道为什么.

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]

推荐答案

添加 order_by 子句以确保它按 number 排序.

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()

这篇关于在 Django 中获取下一个和上一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆