Siddhesh Suthar
Siddhesh Suthar

Reputation: 455

Django ModelField Add default to based on another field in same model while adding a new field

I have this field,

job_created = models.DateTimeField(auto_now_add=True)

Now i want to add something like this, how to base the default on post_created itself. I want the first last_modified to be when job was created, I want something like

last_modified = models.DateTimeField(auto_now=True, default = post_created)

Or if i provide one default while running migrations, how to do that?

Upvotes: 4

Views: 2067

Answers (1)

Sayse
Sayse

Reputation: 43300

Essentially you can't, but you could just create a data migration

def set_last_modified(apps, schema_editor):
    MyModel = apps.get_model('myapp', 'MyModel')

    for obj in MyModel.objects.all():
        obj.last_modified = obj.post_created
        obj.save()


class Migration(migrations.Migration):

    dependencies = [
        ('myapp', 'previous_migration'),
    ]

    operations = [
        # Doesn't need to do anything in reverse, models have not been changed
        migrations.RunPython(set_last_modified, migrations.RunPython.noop)
    ]

You should get the template for this migration by running

migrations --empty yourappname

Upvotes: 8

Related Questions