如何强制Django模型中的2个字段共享相同的默认值而不重复填充方法?

时间:2016-06-14 04:40:01

标签: python django

我有一个Django模型MyModel,如下所示。

它有两个DateTimeField类型的字段:my_field1my_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() 

我希望这两个字段默认为datetime.utcnow()的值。但我想为两者保存 相同的 值。点击utcnow()两次似乎很浪费。

如何设置my_field2的默认值,以便只复制默认值my_field1

我尝试将__init__()方法添加到MyModel,如下所示:

def __init__(self, **kwargs):
    super(MyModel, self).__init__(**kwargs)
    if self.my_field2 is None:
        self.my_field2 = self.my_field1

但正如你所见,这样做打破了模型:

>>> MyModel.objects.all()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "MYvirtualenv/lib/python2.7/site-packages/django/db/models/query.py", line 138, in __repr__
    data = list(self[:REPR_OUTPUT_SIZE + 1])
  File "MYvirtualenv/lib/python2.7/site-packages/django/db/models/query.py", line 162, in __iter__
    self._fetch_all()
  File "MYvirtualenv/lib/python2.7/site-packages/django/db/models/query.py", line 965, in _fetch_all
    self._result_cache = list(self.iterator())
  File "MYvirtualenv/src/django-cache-machine-master/caching/base.py", line 118, in __iter__
    obj = iterator.next()
  File "MYvirtualenv/lib/python2.7/site-packages/django/db/models/query.py", line 255, in iterator
    obj = model_cls.from_db(db, init_list, row[model_fields_start:model_fields_end])
  File "MYvirtualenv/lib/python2.7/site-packages/django/db/models/base.py", line 489, in from_db
    new = cls(*values)
TypeError: __init__() takes exactly 1 argument (2 given)

什么是正确的补救措施? 我需要将my_field2的值默认为my_field1的值(不调用重复调用填充my_field1的默认函数)

1 个答案:

答案 0 :(得分:1)

对我有用的答案:

def save(self, *args, **kwargs):
    if not self.my_field2:
        self.my_field2 = self.my_field1
    super(MyModel, self).save(*args, **kwargs)