How to move a model between two Django apps (Django 1.7)

后端 未结 11 1660
日久生厌
日久生厌 2020-11-28 17:35

So about a year ago I started a project and like all new developers I didn\'t really focus too much on the structure, however now I am further along with Django it has start

11条回答
  •  北海茫月
    2020-11-28 18:01

    How I did it (tested on Django==1.8, with postgres, so probably also 1.7)

    Situation

    app1.YourModel

    but you want it to go to: app2.YourModel

    1. Copy YourModel (the code) from app1 to app2.
    2. add this to app2.YourModel:

      Class Meta:
          db_table = 'app1_yourmodel'
      
    3. $ python manage.py makemigrations app2

    4. A new migration (e.g. 0009_auto_something.py) is made in app2 with a migrations.CreateModel() statement, move this statement to the initial migration of app2 (e.g. 0001_initial.py) (it will be just like it always have been there). And now remove the created migration = 0009_auto_something.py

    5. Just as you act, like app2.YourModel always has been there, now remove the existence of app1.YourModel from your migrations. Meaning: comment out the CreateModel statements, and every adjustment or datamigration you used after that.

    6. And of course, every reference to app1.YourModel has to be changed to app2.YourModel through your project. Also, don't forget that all possible foreign keys to app1.YourModel in migrations have to be changed to app2.YourModel

    7. Now if you do $ python manage.py migrate, nothing has changed, also when you do $ python manage.py makemigrations, nothing new has been detected.

    8. Now the finishing touch: remove the Class Meta from app2.YourModel and do $ python manage.py makemigrations app2 && python manage.py migrate app2 (if you look into this migration you'll see something like this:)

          migrations.AlterModelTable(
          name='yourmodel',
          table=None,
      ),
      

    table=None, means it will take the default table-name, which in this case will be app2_yourmodel.

    1. DONE, with data saved.

    P.S during the migration it will see that that content_type app1.yourmodel has been removed and can be deleted. You can say yes to that but only if you don't use it. In case you heavily depend on it to have FKs to that content-type be intact, don't answer yes or no yet, but go into the db that time manually, and remove the contentype app2.yourmodel, and rename the contenttype app1.yourmodel to app2.yourmodel, and then continue by answering no.

提交回复
热议问题