pythondjangomigrationdatabase-migrationdatabase-management

Should I avoid using models in django migrations?


I am working on an existing Django project that contains migration code like:

someFluffyModel.objects.all().delete()

or

someModel = SomeModel(....)
someModel.save()

Now wherever there is such code and newer migrations change the schema that reflect the current version of the model, there is an issue in applying migrations from scratch.

As I understand the reason is that the model used in the migration doesn't reflect the model used in the migration at that point in time. As I have found fixtures can help in loading data but how about deletion? Is the preferred way to manually delete data from the database?


Solution

  • Sorry forgot to answer my own old question it's been years now but just in case anybody is curious in your migrations you should always be using historical models. The reason is that you get the model at a point in time(reconstructed incrementally base on schema migrations).

    def forwards_func(apps, schema_editor):
        # We get the model from the versioned app registry;
        # if we directly import it, it'll be the wrong version
        Country = apps.get_model("myapp", "Country")
    

    This way if you try to re-run your migrations at some point in the future with model schema x'' old migrations will be run using x' and x depending on their dependencies.

    Avoid importing models to your migrations directly at any cost.

    It is always important to be able to rer-run you migrations since that allows you to migrate forwards backwards between your environments roll back faulty deployments and above all run your tests. If you are doing it wrong your tests will fail at some point when you'll get to schema x' and you'll have to follow the correct approach mentioned above to fix them.

    Thanks to @Daniel Roseman for giving me some pointers that day.