我有一个 Django 模型 MyModel
,如下所示。
它有两个 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() 两次似乎很浪费。
如何设置 my_field2
的默认值,以便它仅复制 my_field1
的默认值?
最佳答案
执行此操作的正确方法是重写 save 方法而不是 __init__ 方法。事实上,不建议覆盖 init 方法,如果您想控制对象的读取方式,更好的方法是覆盖 from_db 或如果您想控制对象的保存方式,则覆盖 save 方法。
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)
更新:我的 claim 引用:https://docs.djangoproject.com/en/1.9/ref/models/instances/
You may be tempted to customize the model by overriding the init method. If you do so, however, take care not to change the calling signature as any change may prevent the model instance from being saved. Rather than overriding init, try using one of these approaches:
关于python - 如何强制 Django 模型中的 2 个字段共享相同的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37782083/