姜戈.如何筛选日期小于当前帖子的帖子



我是编程新手。我不懂方法。在详细查看帖子页面上,我想显示下一篇帖子的列表(即,其时间小于当前帖子的时间(如何访问当前帖子的日期?我尝试:

class PostDetailView(DetailView):
model = Post
slug_field = 'url'
context_object_name = 'post'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['earlier_posts'] = 
Post.objects.filter(publication_date__lte=self.publication_date)
return context

然后我有一个error: 'PostDetailView' object has no attribute 'publication_date'

提前感谢

出现此错误是因为这里的self指的是PostDetailView实例,而不是Post实例。您可以使用DetailView.get_object()获取模型实例

current_post = self.get_object()
context['earlier_posts'] = self.get_queryset().filter(publication_date__lte=current_post.publication_date)

最新更新