Django-Models.DateTimeField-动态更改auto_now_add值 [英] Django - Models.DateTimeField - Changing dynamically auto_now_add value

查看:317
本文介绍了Django-Models.DateTimeField-动态更改auto_now_add值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有DateTimeField的Django模型,其中auto_now_add设置为True。

I have a Django model with a DateTimeField where auto_now_add is set to True. This works well.

class Problem(models.Model):
    ...
    date_created = models.DateTimeField('created on', auto_now_add=True)

创建测试数据时我想或加载历史数据时,绕过此参数(将auto_now_add设置为False)以根据需要设置日期,然后切换回为标准行为(将auto_now_add设置为True )。

I would like, when I create test data or when I load historical data, to bypass this paramater (auto_now_add set to False) to set the date as I want and switch back to the standard behaviour (auto_now_add set to True).

是否有一种方法可以动态更改类(通过更改类的属性?)。此参数对数据库没有影响,并且可能在保存阶段触发。

Is there a way to dynamically change the class (by changing attribute of the class ?). This parameter has no impact on the database and is probably triggered during the save phase.

我不要:-)

date_created = models.DateTimeField('created on', default=timezone.now)

预先感谢

推荐答案

当我从另一个应用程序导入数据时,我也遇到了类似的问题从shell命令执行数据导入脚本的方法。
因为不可能动态禁用auto_now_add或auto_now功能,所以我不得不使用修改后的设置模块。

I faced a similar problem when importing data from another application by means of a data import script being executed from the shell command. Since it isn't possible to disable dynamically the auto_now_add or the auto_now feature, I had to use a modified settings module.

首先,定义一个IMPORT变量在原始设置模块中:

First, defined an IMPORT variable in the original settings module:

IMPORT = False

并创建了一个仅包含以下内容的新import_settings模块:

and created a new import_settings module containing only:

from my_app.settings import *
IMPORT = True

然后,在定义模型时,我添加了代码

Then, in defining my models, I added the code

from django.conf import settings
if settings.IMPORT:
    AUTO_NOW = False
else:
    AUTO_NOW = True

,并在配置DateTimeField时使用了AUTO_NOW的值

and used the value of AUTO_NOW in configuring the DateTimeField

created = models.DateTimeField(editable=False, null=True, blank=True, auto_now_add=AUTO_NOW)
modified = models.DateTimeField(editable=False, null=True, blank=True, auto_now=AUTO_NOW)

最后,我使用manage命令的--settings选项启动了数据导入脚本:

Finally, I launched the data import script using the --settings option of the manage command:

python manage.py shell --settings=my_app.import_settings

这篇关于Django-Models.DateTimeField-动态更改auto_now_add值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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