Search code examples
pythondjangodjango-modelsdjango-migrations

Pre-populate DateTimeField with specific date in django migration


I want to create and pre-populate DateTimeField with specific date for already existing objects.

models.py

    publish_date = models.DateTimeField(verbose_name=_('publish date'))

I try to create a nullable field first, fill it with some data and then remove the null=True from it:

migrations.py

def set_default_publish_date(apps, schema_editor):
    MyModel = apps.get_model('myapp', 'MyModel')
    MyModel.objects.all().update(publish_date=datetime.date(day=1, month=1, year=2019))


class Migration(migrations.Migration):

dependencies = [
    ('myapp', '0005_auto_20200831_1208'),
]

operations = [
    migrations.AddField(
        model_name='mymodel',
        name='publish_date',
        field=models.DateTimeField(null=True, verbose_name='publish date'),
        preserve_default=False,
    ),
    migrations.RunPython(set_default_publish_date, migrations.RunPython.noop),
    migrations.AlterField(
        model_name='mymodel',
        name='publish_date',
        field=models.DateTimeField(verbose_name='publish date'),
        preserve_default=False,
    ),
]

As a result of running migrations I get an error:

django.db.utils.OperationalError: cannot ALTER TABLE "myapp_mymodel" because it has pending trigger events

What can I do to fix it?


Solution

  • Just split your migrations up to into 2 or possibly 3. You should be able to do the first 2 actions in one mig but not the 3rd.