我想从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?
答案 0 :(得分:4)
默认值应为timedelta。这是Django中的一个错误,并设置为在1.8.1版本中修复。 请参阅:https://code.djangoproject.com/ticket/24566
所以pause = DurationField(default=timedelta(minutes=20))
应该使用1.8.1版本。
答案 1 :(得分:1)
你略微混淆了事情的顺序:
pause = DurationField(default=int(timedelta(minutes=20).total_seconds()))
如上所述,整数没有total_seconds()
属性。相反,它是instance method of timedelta
。