Django: durationField default value
Question:
What’s the right way to use Django’s DurationField
?
When I use time_passed = models.DurationField(default=0)
:
- Migrations work
- Form defaults don’t work (
'int' object has no attribute 'total_seconds'
)
When I use time_passed = models.DurationField(default=timedelta())
:
- Migrations don’t work (
ValueError: Cannot serialize: datetime.timedelta(0)
)
- Form defaults work
So what is the right way to use a default value on duration field or a workaround for this issue?
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 using default should be:
from datetime import timedelta
time_passed = models.DurationField(default=timedelta)
MatZeg’s answer on this similar question shows that you can still pass in arguments as well:
pause = DurationField(default=timedelta(minutes=20))
What’s the right way to use Django’s DurationField
?
When I use time_passed = models.DurationField(default=0)
:
- Migrations work
- Form defaults don’t work (
'int' object has no attribute 'total_seconds'
)
When I use time_passed = models.DurationField(default=timedelta())
:
- Migrations don’t work (
ValueError: Cannot serialize: datetime.timedelta(0)
) - Form defaults work
So what is the right way to use a default value on duration field or a workaround for this issue?
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 using default should be:
from datetime import timedelta
time_passed = models.DurationField(default=timedelta)
MatZeg’s answer on this similar question shows that you can still pass in arguments as well:
pause = DurationField(default=timedelta(minutes=20))