How can I force 2 fields in a Django model to share the same default value?

放肆的年华 提交于 2019-11-28 14:20:46

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)

Update: Reference for my 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:

As stated in the docs:

The default value is used when new model instances are created and a value isn’t provided for the field.

So to solve your task, I would fill the default values manually in the __init__. Something like:

def __init__(self, *args, **kwargs):
    now = datetime.datetime.utcnow()
    kwargs.setdefault('my_field1', now)
    kwargs.setdefault('my_field2', now)
    super(MyModel, self).__init__(*args, **kwargs)

Alternatively you can handle the values in save method.

If you want my_field2 to have any value that is in my_field1, I would go with this solution:

class MyModel(models.Model):
    my_field1 = models.DateTimeField(default=datetime.utcnow, editable=False)
    my_field2 = models.DateTimeField()

    def __init__(self, **kwargs):
        super(MyModel, self).__init__(**kwargs)
        if self.my_field2 is None:
            self.my_field2 = self.my_field1
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!