Migrate-Problem with models.DurationField()

Hello,
I have a problem, when I add a models.DurationField() to an existing Model, then I get an AttributeError with ./manage migrate

return (24 * 60 * 60 * delta.days + delta.seconds) * 1000000 + delta.microseconds
AttributeError: ‘int’ object has no attribute ‘days’

Python 3.7.3
Django==3.2.10
As Database I use default sqlite3

Reproduction:

  1. Start new project
  2. Create new app
  3. Add app to Installed_apps
  4. Create a Model
class Durtest(models.Model):
    name = models.CharField(max_length=20)
  1. run ./manage makemigrations and ./manage migrate
  2. Add an DurationField to the existing Model:
from django.db import models
from datetime import timedelta

class Durtest(models.Model):
    name = models.CharField(max_length=20)
    dur = models.DurationField()
  1. I run ./manage makemigration.
You are trying to add a non-nullable field 'dur' to durtest without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py

I choose 1) and input 0.

  1. On ./manage migrate again, then I got an error:

File “/********/env/lib/python3.7/site-packages/django/utils/duration.py”, line 44, in duration_microseconds
return (24 * 60 * 60 * delta.days + delta.seconds) * 1000000 + delta.microseconds
AttributeError: ‘int’ object has no attribute ‘days’

  1. When I change to
 dur = models.DurationField(default=timedelta(seconds=0))

the error will show again.

The error does not occur, when the DurationField exists in the initial migration. What make I wrong? Can anyone help?

Please can you share more levels of your stack traces? It will make it easier to determine if there’s a bug in Django or not.

Also, the contents of your migration files.

Stacktrace:

/manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, dt, sessions
Running migrations:
  Applying dt.0002_durtest_dur...Traceback (most recent call last):
  File "./manage.py", line 22, in <module>
    main()
  File "./manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "******/durtest/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "******/durtest/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "******/durtest/env/lib/python3.7/site-packages/django/core/management/base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "******/durtest/env/lib/python3.7/site-packages/django/core/management/base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "******/durtest/env/lib/python3.7/site-packages/django/core/management/base.py", line 89, in wrapped
    res = handle_func(*args, **kwargs)
  File "******/durtest/env/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 246, in handle
    fake_initial=fake_initial,
  File "******/durtest/env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "******/durtest/env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "******/durtest/env/lib/python3.7/site-packages/django/db/migrations/executor.py", line 227, in apply_migration
    state = migration.apply(state, schema_editor)
  File "******/durtest/env/lib/python3.7/site-packages/django/db/migrations/migration.py", line 126, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "******/durtest/env/lib/python3.7/site-packages/django/db/migrations/operations/fields.py", line 106, in database_forwards
    field,
  File "******/durtest/env/lib/python3.7/site-packages/django/db/backends/sqlite3/schema.py", line 330, in add_field
    self._remake_table(model, create_field=field)
  File "******/durtest/env/lib/python3.7/site-packages/django/db/backends/sqlite3/schema.py", line 191, in _remake_table
    self.effective_default(create_field)
  File "******/durtest/env/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 324, in effective_default
    return field.get_db_prep_save(self._effective_default(field), self.connection)
  File "******/durtest/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 842, in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "******/durtest/env/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 1617, in get_db_prep_value
    return duration_microseconds(value)
  File "******/durtest/env/lib/python3.7/site-packages/django/utils/duration.py", line 44, in duration_microseconds
    return (24 * 60 * 60 * delta.days + delta.seconds) * 1000000 + delta.microseconds
AttributeError: 'int' object has no attribute 'days'

0001_initial.py

# Generated by Django 3.2.10 on 2021-12-22 14:45

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Durtest',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=20)),
            ],
        ),
    ]

0002_durtest_dur.py

# Generated by Django 3.2.10 on 2021-12-22 14:45

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('dt', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='durtest',
            name='dur',
            field=models.DurationField(default=0),
            preserve_default=False,
        ),
    ]

0003_alter_durtest_dur.py

# Generated by Django 3.2.10 on 2021-12-22 14:46

import datetime
from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('dt', '0002_durtest_dur'),
    ]

    operations = [
        migrations.AlterField(
            model_name='durtest',
            name='dur',
            field=models.DurationField(default=datetime.timedelta(0)),
        ),
    ]

Ok, so the root cause was you adding a default value of 0 when asked for a default value for the migration:

default = 0 isn’t valid here.

Since this migration did not apply, you’ve got at least two options:

  • Delete these two migrations (0002 and 0003) and recreate them. (Since you’ve added the default to the field definition, you shouldn’t be asked that question again.)

  • Edit 0002 and replace the default with the default from 0003.

3 Likes