私は、publication_date フィールドと is_published フィールドを持つ Django モデルを持っています。このモデルのマネージャーを作成しました。これは公開されたすべてのアイテムを返します。つまり、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 built を使用) - サーバー atm 内)。私はアムステルダム時間 (+2:00) にいて、publication_date フィルターに 2 時間を追加すると問題なく動作するので、日時の認識に慣れていないので、何か間違ったことをしていると思います。ブラケットの有無にかかわらず timezone.now を試しましたが、違いはありません。