4

我想将默认值从 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?

4

2 回答 2

6

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

所以pause = DurationField(default=timedelta(minutes=20)) 应该与 1.8.1 版本一起使用。

于 2015-04-20T06:42:55.773 回答
1

你稍微混淆了事情的顺序:

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

如前所述,整数没有total_seconds()属性。相反,它是一个实例方法timedelta

于 2015-04-16T10:29:46.893 回答