1
class ModelA:
    pass

class ModelB:
    model_a = ForeignKey(ModelA)

If I want to rename ModelA to ModelANew here is the strategy Django Follows:

  1. Migration 1: Create ModelANew
  2. Migration 2:
    • Remove field model_a from ModelB.
    • Add field model_a_new to ModelB
  3. Migration 3: Delete ModelA

The obvious downside of this is that the information in the table modela is lost. Can this be done with renaming the model? Django obviously did not ask if this was a rename. Is it possible to inform or make it go that route? If not, what would be a strategy to manually code the migration.

mehmet
  • 7,720
  • 5
  • 42
  • 48
  • There's an answer to this here: https://stackoverflow.com/questions/27175106/renaming-modelstables-in-django – Tom Carrick May 09 '20 at 13:28
  • @TomCarrick: That question is very very old (2014). I doubt Django had migrations then, let alone `RenameModel`. – mehmet May 09 '20 at 13:31
  • It has an answer from 2017. Migrations were introduced in 2015. The answer uses a migration operation that existed then and exists now. – Tom Carrick May 09 '20 at 13:35
  • Also your question seems contradictory to me. The title states "instead of rename" but in the question body it seems clear that you want to rename it rather than dropping the data. – Tom Carrick May 09 '20 at 13:39
  • @TomCarrick: title describes the problem. it is true that I need a rename. The answer that you linked pretty much says "create an empty migration and code it by hand". Doesn't really answer my question. – mehmet May 09 '20 at 13:55
  • Yes it does. It's a simple migration to write. It renames the model. It's _much_ less effort than any other way. What is your problem with it? – Tom Carrick May 09 '20 at 14:21
  • @TomCarrick I don't have a problem with manually writing the migration. If you read the posting, it clearly asks for a strategy to make this happen. You are more than welcome to provide an answer. – mehmet May 11 '20 at 12:12

1 Answers1

0

Migration 1.

Create ModelANew model.

Migration 2.

Create data migration. Migrate data to new Model.

Migration 3.

Delete old Model.

Tigran
  • 632
  • 1
  • 5
  • 21