问题
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