Search code examples
pythondjangopostgresqldjango-migrations

Django migrations -- how do I wipe a model as part of a migration?


I have a workflow where a model is generated by a script from some data also stored in the database:

SourceData -> management command generates -> Results

When I change how that Results model is generated, like adding a new field, I don't want to set a default value or update the existing models, I want to delete all of them and just run the script again to regenerate them with the new field:

Delete all Results -> run management command v2 -> Results (+ new field)

Is there an easy way to do this? All I've found online is how to accomplish this by deleting the whole database, which isn't what I want, I just want to drop this one table and recreate it.


Solution

  • Couldn't figure out The Right Way to do it, but managed to hack it by:

    • Start with a clean git history (no dirty files) -- makes the next steps easier
    • Rename the model in question to something else, like Model2
    • Run makemigrations
    • Revert all changes except the generated migration
    • Reorder the generated migration file so DeleteModel comes before CreateModel, and change the name of the model being created in CreateModel back to the original model name. It should look like this:
    class Migration(migrations.Migration):
    
        dependencies = [
            ("<app name>", "<previous migration>"),
        ]
    
        operations = [
            migrations.DeleteModel(
                name="ModelName",
            ),
            migrations.CreateModel(
                name="ModelName",
                fields=[
                    # < all fields of your model >
                ],
                options={
                    # < all meta options of your model >
                },
            ),
        ]