我正在尝试编写模型管理器以获取已发布的所有条目,并且start_date位于now
的过去。奇怪的是,如果我将日期设置为过去的值(1分钟之前),一切正常,但如果我将来设置日期(提前1分钟),即使我等待更多,对象也不会显示超过1分钟进行测试。如果我只是重新启动服务器,则会显示该条目。但是每次发布条目时我都无法重启服务器。
任何人都能看到这段代码有什么问题吗?或者可以这样做吗?
from django.utils import timezone
now = timezone.now()
def entries_published(queryset):
"""Return only the entries published"""
return queryset.filter(
models.Q(start_publication__lte=now) | \
models.Q(start_publication=None),
models.Q(end_publication__gt=now) | \
models.Q(end_publication=None),
status=PUBLISHED)
class EntryPublishedManager(models.Manager):
"""Manager to retrieve published entries"""
def get_queryset(self):
"""Return published entries"""
return entries_published(
super(EntryPublishedManager, self).get_queryset())
class Entry(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255)
categories = models.ManyToManyField(Category, related_name='entries', blank=True, null=True)
creation_date = models.DateTimeField(auto_now_add=True)
start_publication = models.DateTimeField(blank=True, null=True, help_text="Date and time the entry should be visible")
end_publication = models.DateTimeField(blank=True, null=True, help_text="Date and time the entry should be removed from the site")
status = models.IntegerField(choices=STATUS_CHOICES, default=DRAFT)
objects = models.Manager()
published = EntryPublishedManager()
我的观点是这样的:
class EntryListView(ListView):
context_object_name = "entry_list"
paginate_by = 20
queryset = Entry.published.all().order_by('-start_publication')
如果我在now = timezone.now()
的def中移动entries_published
,则CategoryDetail
视图会获得正确的已发布条目。知道为什么EntryListView
没有显示正确的那些?
这是我的CategoryDetail
视图
#View for listing one category with all connected and published entries
class CategoryDetail(ListView):
paginate_by = 20
def get_queryset(self):
self.category = get_object_or_404(Category, slug=self.kwargs['slug'])
return Entry.published.filter(categories=self.category).order_by('-start_publication', 'title')
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(CategoryDetail, self).get_context_data(**kwargs)
# Add in the category
context['category'] = self.category
return context
如果我将EntryListView
更改为:
class EntryListView(ListView):
model = Entry
context_object_name = "news_list"
paginate_by = 20
def get_queryset(self):
return Entry.published.all().order_by('-start_publication')
一切正常。奇怪,但我不在乎。
答案 0 :(得分:0)
编辑: 我认为您的问题现在是= timezone.now()在您启动应用程序时设置。在entries_published方法中定义'now'。
添加了: 我建议简化你的方法,以确保调用类方法并完全跳过函数定义。
class EntryPublishedManager(models.Manager):
"""Manager to retrieve published entries"""
def get_queryset(self):
now = timezone.now()
return Super(EntryPublishedManager, self).get_queryset().filter(
models.Q(start_publication__lte=now) | \
models.Q(start_publication=None),
models.Q(end_publication__gt=now) | \
models.Q(end_publication=None),
status=PUBLISHED)