django在QuerySet中给定当前对象获取下一个对象
我有一个章节模型,因此在章节详细信息视图中,我希望用户能够导航到下一章和上章,因为他正在查看当前章节,所以这是在Django中最有效的方法,
这是我的章节模型
class Chapter(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(blank=True,null=True,)
module = models.ForeignKey(Module,on_delete=models.CASCADE,null=True,blank=True,)
content = models.TextField()
def __str__(self):
return self.title
i have seen some answers while they use the python list method to turn the queryset in to an array but i think maybe there is a better way
I have a chapter model so in the chapter detail view i want the user to be able to navigate to the next and to previous chapter given the current chapter that he's viewing so what's is the most efficient way to that in django
this is my chapter model
class Chapter(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(blank=True,null=True,)
module = models.ForeignKey(Module,on_delete=models.CASCADE,null=True,blank=True,)
content = models.TextField()
def __str__(self):
return self.title
i have seen some answers while they use the python list method to turn the queryset in to an array but i think maybe there is a better way
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我要谨慎使用ID作为位置标识符,因为只有连续创建章节时才可靠 - 您不能创建一个章节模块,然后在第一个模块上添加最后一章,您可以't重新排列章节。我将模型扩展到包含订单字段,
在模型中
唯一的模块,然后您 定义get_next_chapter方法(get get上一章都可以使用类似)
,但是...虽然这将起作用,但每个引用它是另一个数据库调用。为了提高效率,您可以在视图中使用订单号来在单个查询中获取所有相关章节,例如
views.py
,然后在模板中获取所有相关章节
I'd be careful about using id as a positional identifier, as that is only dependable if chapters are created consecutively - you can't create one module of chapters, then another, then add a final chapter on the first module, and you can't rearrange chapters later. I'd extend the model to include a order field, unique for module
in your model
Then you could define a get_next_chapter method (get previous chapter would work similarly)
But...while this will work, each reference to it is another database call. To be more efficient, you could utilise the ordering number in your view to get all the relevant chapters in a single query, eg:
views.py
and then in your template
我考虑了分页,但我写了最快的方式。
在HTML中,
您需要在章节循环中调用
get_next
。我认为您的章节URL为详细信息/< id>
I thought about pagination but I wrote the fastest way.
in HTML
You need to call
get_next
in chapter objects loop. I suppose your chapter URL asdetail/<id>
您可以在细节视图的背景下提供它们。例如,例如以下方法,例如以下方法,例如
以下方法,presurn_chapter和next_ chapter可能是在模型中定义URL.py如下
和章节详细信息页面模板,假设上下文对象名称为current_ chapter
You can provide them in a context of detail view. For example like previous_chapter, current_chapter and next_chapter as follow
Another approach may be defining urls in models.py as follow
And in chapter detail page template assuming context object name as current_chapter