Django DurationField default
Asked Answered
N

2

4

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?

Nostril answered 16/4, 2015 at 10:24 Comment(1)
I don't have a answer, this might be a bug. But see this ticket: code.djangoproject.com/ticket/24445, where a core django developer says: "you should provide a timedelta value for your DurationField default value".Guinea
F
6

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.

Fulsome answered 20/4, 2015 at 6:42 Comment(0)
E
1

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.

Eleventh answered 16/4, 2015 at 10:29 Comment(1)
sorry, mistake in qestion, I tried int(timedelta(minutes=20).total_seconds())Nostril

© 2022 - 2024 — McMap. All rights reserved.