I have a Django model MyModel
as shown below.
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?
)
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.
How can I set the default value of my_field2
so that it simply copies the default value of my_field1
?
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
来源:https://stackoverflow.com/questions/37782083/how-can-i-force-2-fields-in-a-django-model-to-share-the-same-default-value