我有一个名为Post的模型,如下所示:
class Post(models.Model):
title = models.CharField(max_length=18)
body = models.TextField()
date = models.DateTimeField()
def __str__(self):
return self.title
我如何获得上一个和下一个Post对象?
我尝试减去1并添加1以在 views.py 中查找.objects.get(id)
:
def blog_detail(request, id):
post = Post.objects.get(id)
post_id = post.id
previous_post_id = int((post.id-1))
next_post_id = int((post.id+1))
# Next post
try:
next_post = Post.objects.get(id=next_post_id)
except:
next_post = None
# Previous Post
try:
previous_post = Post.objects.get(id=previous_post_id)
except:
previous_Post = None
context = {'post': post, 'next': next_post, 'previous_post': previous_post}
return render(request, "BlogHome/pages/post.html", context)
我假设我对语法的工作原理有误解。
答案 0 :(得分:2)
您不能依赖具体的ID来存在于数据库中。它们可能已被删除或者pk序列可能已被操纵,或者由于事务失败而可能已跳过它们。您可以执行以下操作:
# None if there's no previous
previous_post = Post.objects.filter(id__lt=post.id).order_by('-id').first()
# None if there's no next
next_post = Post.objects.filter(id__gt=post.id).order_by('id').first()
第一个查询获取的Post
实例最大id
小于post
' s id
(如果存在)。请注意,get_next_by_FOO方法仅适用于DateField
和DateTimeField
。因此,您可以使用:
previous_post = post.get_previous_by_date()
next_post = post.get_next_by_date()
# both use id as tie-breaker
但是,如果没有下一个/上一个,这些将引发异常。