问题描述
我有一个 Django 模型 MyModel
,如下所示.
I have a Django model MyModel
as shown below.
它有两个 DateTimeField 类型的字段:my_field1
, my_field2
It has two fields of type DateTimeField: my_field1
, my_field2
from django.db import models
from datetime import datetime
class MyModel(models.Model):
my_field1 = models.DateTimeField(default=datetime.utcnow, editable=False)
my_field2 = models.DateTimeField(
# WHAT DO I PUT HERE?
)
我希望两个字段都默认为 datetime.utcnow()
的值.但我想为两者保存相同的值.两次调用 utcnow()
似乎很浪费.
I want both fields to default to the value of datetime.utcnow()
. But I want to save the same value for both. It seems wasteful to call utcnow()
twice.
如何设置my_field2
的默认值,使其简单地复制my_field1
的默认值?
How can I set the default value of my_field2
so that it simply copies the default value of my_field1
?
推荐答案
正确的方法是重写 save 方法而不是 __init__
方法.实际上,不建议覆盖 init 方法,如果您希望控制对象的读取方式,则更好的方法是覆盖 from_db 或如果您想控制对象的保存方式,则覆盖 save 方法.
The proper way to do this is by over riding the save method rather than the __init__
method. In fact it's not recommended to over ride the init method, the better way is to over ride from_db if you wish to control how the objects are read or save method if you want to control how they are saved.
class MyModel(models.Model):
my_field1 = models.DateTimeField(default=datetime.utcnow, editable=False)
my_field2 = models.DateTimeField()
def save(self, *arges, **kwargs):
if self.my_field1 is None:
self.my_field1 = datetime.utcnow()
if self.my_field2 is None:
self.my_field2 = self.my_field1
super(MyModel, self).save(*args, **kwargs)
更新:我的声明参考:https://docs.djangoproject.com/en/1.9/ref/models/instances/
您可能会想通过覆盖 init 来自定义模型方法.但是,如果您这样做,请注意不要更改调用签名,因为任何更改都可能阻止模型实例保存.与其覆盖 init,不如尝试使用其中之一方法:
这篇关于如何强制 Django 模型中的 2 个字段共享相同的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!