Django似乎正在缓存datetime.now() [英] Django seems to be caching datetime.now()

查看:134
本文介绍了Django似乎正在缓存datetime.now()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的模型:

I have a model that looks like this:

class Item(models.Model):
    ...
    publish_date = models.DateTimeField(default=datetime.datetime.now)
    ...

并且一个看起来像这样的经理:

And a manager that looks like this:

from datetime import datetime

class ItemManager(Manager):
    def published(self):
        return self.get_query_set().filter(publish_date__lte=datetime.now()

并且一个看起来像这样的视图:

And a view that looks like this:

class ItemArchive(ArchiveIndexView):
    queryset = Item.objects.published()
    date_field = 'publish_date'

想法是我可以调用 Item.objects.published()并获取所有已发布的项目的查询集

The idea being that I can call Item.objects.published() and get a queryset of all published Items.

问题是Django似乎在管理器中执行 datetime.now()调用服务器启动和启动唤醒这个价值。所以如果今天是5月24日,我创建了一个项目,发布日期为5月23日,并在5月22日开始服务器,那5月23日的项目不会出现 ItemArchive 视图。一旦我重新启动Apache,5月23日的项目会正确显示在视图中。

The problem is that Django seems to be executing the datetime.now() call in the manager when the server is started and then caching that value. So if today is May 24th, and I created an Item with a publish date of May 23rd, and started the server on May 22nd, that May 23rd item will not show up in the ItemArchive view. As soon as I restart Apache, the May 23rd item shows up in the view correctly.

如何强制Django执行 datetime.now( )

How can I force Django to execute datetime.now() every time the manager is called?

推荐答案

我相信这是由您的视图定义 queryset = Item.objects.published()作为一个类变量。当您的 ItemArchive 类最初被导入时,该行将执行一次。您应该将该行移动到每次调用视图时执行该行的方法。

I believe this is caused by your view defining queryset = Item.objects.published() as a class variable. This line will be executed once, when your ItemArchive class is initially imported. You should move that line into a method where it will be executed each time a view is called.

这篇关于Django似乎正在缓存datetime.now()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆