How to let existing entries empty when using auto_now_add?

陌路散爱 提交于 2019-12-11 17:12:37

问题


I added a field to my existing model :

    creation_date = models.DateTimeField(
        auto_now_add=True,
        blank=True, null=True)

The resulting file after makemigrations looks like

    migrations.AddField(
        model_name='document',
        name='creation_date',
        field=models.DateTimeField(auto_now_add=True, null=True),
    ),

When applying the migration, auto_now_add is applied to all existing entries.

How to avoid that ? creation_date must remain null for all data recorded before the migration is applied.


回答1:


The easiest is probably to revert the migration, in the migration file. So you first run:

./manage.py makemigrations

but you do not (!) yet migrate. You can then inspect the migration file, and alter it to:

# Generated by Django 2.2.2 on 2019-07-11 15:55

from django.db import migrations, models


def set_to_null(apps, schema_editor):
    SomeModel = apps.get_model("app", "SomeModel")
    SomeModel.objects.update(creation_date=None)


class Migration(migrations.Migration):

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

    operations = [
        migrations.AddField(
            model_name='somemodel',
            name='creation_date',
            field=models.DateTimeField(auto_now_add=True, null=True),
        ),
        migrations.RunPython(set_to_null),
    ]

Then you thus can migrate your database. It will first construct an extra field, and then set the creation_date column, for existing records, with set_to_null, to NULL.



来源:https://stackoverflow.com/questions/56992825/how-to-let-existing-entries-empty-when-using-auto-now-add

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!