我有一个 Django 模型,它有一个 publication_date 和一个 is_published 字段。我为此模型创建了一个管理器,它返回所有已发布的项目,这意味着:每个具有 is_published=True 和 publication_date <= now 的项目。
class PublishedTextManager(models.Manager):
"""
Filters out all unpublished items and items with a publication date in the future
"""
def get_query_set(self):
return super(PublishedTextManager, self).get_query_set() \
.filter(is_published=True) \
.filter(publication_date__lte=timezone.now())
使用此管理器的视图如下所示:
class NewsAndEventsOverView(ListView):
model = News
queryset = News.published.all().order_by('-publication_date')
context_object_name = 'news_list'
def get_context_data(self, **kwargs):
# Initialize context and fill it with default data from NewsAndEventsOverView super class
context = super(NewsAndEventsOverView, self).get_context_data(**kwargs)
# Add view specific context
context['latest_news_item'] = context['news_list'][0]
today = timezone.now()
yesterday = today - timedelta(days=1)
context['upcoming_events_list'] = Event.published.filter(Q(date_end__gt=yesterday) | Q(date_start__gt=yesterday)).order_by('date_start')
past_events_list = Event.published.filter(Q(date_end__lt=today) | Q(date_start__lt=today)).order_by('-date_start')
old_news_list = context['news_list'][1:]
context['old_news_and_events_list'] = sorted(chain(old_news_list, past_events_list), key=lambda x: x.publication_date, reverse=True)
return context
相关urls.py:
from .views import NewsAndEventsOverView
urlpatterns = patterns('',
# Index page
url(r'^$', NewsAndEventsOverView.as_view(), name="newsandevents_overview"),
)
当我默认添加新闻项目时,它会接收当前日期时间(timezone.now())作为发布日期,但是当我刷新页面时,它不会显示在前端,直到我重新启动服务器(使用 django 构建-在服务器自动取款机)。我在阿姆斯特丹时间(+2:00),当我在 publication_date 过滤器中添加 2 小时时,它工作正常,所以由于我是日期时间意识的新手,我猜我做错了什么。我已经尝试了带和不带括号的 timezone.now,但这并没有什么不同。