Django DurationField default

岁酱吖の 提交于 2019-12-07 16:31:01

问题


I want to pass default value into DurationField from django 1.8. According to documentation it should be datetime.timedelta

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

But on makemigrations it says:

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

Ok. Maybe we should pass integer?

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

or:

pause = DurationField(default=20*60)

makemigrations runs ok, but on object creation I see:

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'

So it want timedelta?


回答1:


The default should be a timedelta. This is a bug in Django and is set to be fixed in the 1.8.1 release. See: https://code.djangoproject.com/ticket/24566

So pause = DurationField(default=timedelta(minutes=20)) Should work with the 1.8.1 release.




回答2:


You mixed up the order of things slightly:

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

As mentioned, integers don't have a total_seconds() attribute. Rather, it is an instance method of timedelta.



来源:https://stackoverflow.com/questions/29671903/django-durationfield-default

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!