在 django的 DetailView页面想要做到下一篇文章的链接,我的思路是获取当前 object的先一个object或后一个object。查了一下 django documentation,找到如下信息。
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.
也就是说,当某 field为 DateField或 DateTimeField时,就可以查询其相邻的 object,假设这个 field的命名为foo, 那么查询下一个 object的方法就是 get_next_by_foo(),查询先一个 object的方法就是 get_previous_by_foo(),即 obj_next = obj.get_next_by_foo(), obj_prev = obj.get_previous_by_foo()。
class ArticleDetailView(DetailView):
...
def get_context_data(self, **kwargs):
context = super(ArticleDetailView, self).get_context_data(**kwargs)
obj = super(ArticleDetailView, self).get_object()
try:
obj_next = obj.get_previous_by_modify()
context['slug_next'] = obj_next.slug
except:
context['slug_next'] = obj.slug + "/#"
try:
obj_prev = obj.get_next_by_modify()
context['slug_prev'] = obj_prev.slug
except:
context['slug_prev'] = obj.slug + "/#"
return context