Django DurationField 默认值

Django DurationField default

我想将默认值从 django 1.8 传递到 DurationField。根据文档,它应该是 datetime.timedelta

from datetime import timedelta
pause = DurationField(default=timedelta(minutes=20))

但是在 makemigrations 上它说:

ValueError: Cannot serialize: datetime.timedelta(0, 1200)
There are some values Django cannot serialize into migration files.

好的。也许我们应该传递整数?

pause = DurationField(default=int(timedelta(minutes=20).total_seconds()))

或:

pause = DurationField(default=20*60)

makemigrations 运行正常,但在创建对象时我看到:

for obj in self.query.objs
  File "/home/web/django_env/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 920, in <listcomp>
    for obj in self.query.objs
  File "/home/web/django_env/lib/python3.4/site-packages/django/db/models/sql/compiler.py", line 918, in <listcomp>
    ) for f in fields
  File "/home/web/django_env/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 710, in get_db_prep_save
    prepared=False)
  File "/home/web/django_env/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1683, in get_db_prep_value
    return value.total_seconds() * 1000000
AttributeError: 'int' object has no attribute 'total_seconds'

所以它需要 timedelta?

你稍微搞错了顺序:

pause = DurationField(default=int(timedelta(minutes=20).total_seconds()))

如前所述,整数没有 total_seconds() 属性。相反,它是一个 instance method of timedelta.

默认值应该是时间增量。这是 Django 中的一个错误,将在 1.8.1 版本中修复。 参见:https://code.djangoproject.com/ticket/24566

所以pause = DurationField(default=timedelta(minutes=20)) 应该适用于 1.8.1 版本。