Перенос Модели в DJANGO

Moving a Django model to another app can be tricky. Here is a quick rundown of the most convenient way I found so far. The idea is to simply rename the database tables, and force Django to consider this the new state of your models. Thanks to Marten Kenbeek who pointed me at SeparateDatabaseAndState.

This is probably still missing some edge cases and I only tested it on one project, so be careful.

  1. Create a backup.
  2. Copy the model code to the new app. Update any foreign key references as necessary.
  3. Run manage.py makemigrations new_app
  4. Edit the migration:
  1. Delete the models from the old app.
  2. Run manage.py makemigrations old_app
  3. Edit the migration:

manage.py migrate

Вариант для версии 1.7

This can be done fairly easily using migrations.SeparateDatabaseAndState. Basically, we use a database operation to rename the table concurrently with two state operations to remove the model from one app’s history and create it in another’s.

Remove from old app

python manage.py makemigrations old_app --empty

In the migration:

Add to new app

First, copy the model to the new app’s model.py, then:

python manage.py makemigrations new_app

This will generate a migration with a naive CreateModel operation as the sole operation. Wrap that in a SeparateDatabaseAndState operation such that we don’t try to recreate the table. Also include the prior migration as a dependency:

Мое решение

Удалил базу данных, удалил все миграции выполнил миграции заново и пере залил данные

Проблемы с существующими таблицами

If you have the table created in the database, you can run

python manage.py migrate --fake <appname>

Mark migrations as run without actually running them

Обсуждение закрыто.