Skip to main content
 首页 » 编程设计

python之Django YearArchiveView 能否返回所有可能年份的列表

2024年11月01日36xxx_UU

我正在使用 YearArchiveView 使用我创建的应用程序在页面上显示每年的所有评论:

class year_reviews(YearArchiveView): 
    queryset = SimpleReview.objects.published() 
    date_field = "date_published" 
    make_object_list = True 
    allow_future = False 
    template_name = 'reviews.html' 
    context_object_name = 'reviews' 

该 View 工作正常 - 它正确返回 URL 中指定年份的所有评论,不显示 future 的评论,并且只显示已发布的评论。

在呈现页面的顶部,我想列出所有年份的评论,以便用户可以轻松地转到不同年份的评论。 YearArchiveView 自动为模板提供 next_year 和 previous_year 上下文变量,但我找不到任何可用年份的列表。 date_list 看起来很有希望,但只返回所选年份内 月 的列表。

有没有什么方法可以获取 View 可以显示的所有年份的列表,以便为 View 提供页面之间的导航?

请您参考如下方法:

是的 - dates 查询集可以做到这一点:

https://docs.djangoproject.com/en/dev/ref/models/querysets/#dates

它看起来不像通用 View 中的任何东西已经运行了这样的查询,所以您可能希望将它放在您的 get_context_data 方法中。

你会想要这样的东西:

class YearReviews(YearArchiveView): 
 
    def get_context_data(self, **kwargs): 
        context = super(YearReviews, self).get_context_data(**kwargs) 
        context['years_available'] = self.queryset.dates(self.date_field, 'year') 
        return context 

这会将 datetime.date 对象的查询集放入您的上下文中,代表每个有效年份的 1 月 1 日。如果愿意,您可以在 get_context_data 方法中将它们变成年份字符串,或者在您的模板中使用 |date 过滤器。它会忽略您的 allow_future 设置 - 如果您根据实时发布日期,这可能不是什么大问题。