Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django DurationField default

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?

like image 686
Ivan Borshchov Avatar asked Mar 16 '23 10:03

Ivan Borshchov


2 Answers

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.

like image 137
MatZeg Avatar answered Mar 23 '23 13:03

MatZeg


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.

like image 27
rnevius Avatar answered Mar 23 '23 13:03

rnevius