0

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?

anjaneyulubatta505
  • 7,742
  • 1
  • 32
  • 50
Andreas
  • 641
  • 10
  • 24
  • do you have existed migrations already ? – anjaneyulubatta505 Mar 30 '18 at 12:45
  • 1
    This is all fully documented. Use the frozen versions of the models that are available within the migration. – Daniel Roseman Mar 30 '18 at 12:54
  • going back to the docs though this doesn't need to be done manually but maybe loading models via ` apps.get_model('blog', 'Post')` could do the trick pardon my ignorance I am new to django and I am dealing with third party code xD – Andreas Mar 30 '18 at 13:27
  • @DanielRoseman thanks for the pointer that worked :) (and also for not giving away the full answer since that's the best way to learn) – Andreas Mar 30 '18 at 13:47

1 Answers1

0

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.

Andreas
  • 641
  • 10
  • 24