如何在Django模型中强制2个字段共享相同的默认值? [英] How can I force 2 fields in a Django model to share the same default value?

查看:161
本文介绍了如何在Django模型中强制2个字段共享相同的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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?

推荐答案

正确的方式是通过保存方法而不是 __ init __ 方法。实际上,不建议您使用 init 方法,如果要控制如何控制如何保存对象,更好的方法是如何控制对象的读取或保存方法。

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 ,请尝试使用以下
方法之一:

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:

这篇关于如何在Django模型中强制2个字段共享相同的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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