Evgenii Legotckoi
April 24, 2019, 1:42 p.m.

Django - Tutorial 045. How to move model from one application to another

I would like to share one of the possible way for moving the data model from one application to another.

Immediately, I note that this version of the data model transfer is not 100% working and you may need additional manual editing of the tables to correctly set the Content Type. Since any such modifications are fraught with data loss for GenericForeignKey relationships.

In my case, GenericForeignKey was not used, so there was no such problem.


Initial data

Suppose you have an old article article that has the Article model. You need to create a blog application and transfer the Article model to this application. Uses PostgreSQL database.

Moving a model

  1. Make a backup copy of the database (backup), you can make a database dump and practice on this dump on the development server.

  2. Move the model code Article from article.models.py to blog.models.py . That is, the code from the old model must be removed.

  3. Edit the Meta class in the Article model to keep the old table name. In this case, it was article_artilce

    1. class Meta:
    2. db_table = 'article_article'

  4. Change all references to data models in the whole project. This means change all imports and ForeignKey .

  5. Create migrations for both applications in the following order.

    1. python manage.py makemigrations blog
    2. python manage.py makemigrations article

  6. Apply migration in fake mode. This will allow you to add migrations as applied, but no changes will be made.

    1. python manage.py migrate --fake

    At the moment, the database will be vulnerable in that it was not created Content Type for your transferred data model.

  7. This can be corrected by the following actions. Now we need to change the name of the table, and this can be done by removing db_table from the data model and creating and applying a new migration to the new application. Content Type will be created automatically when migration is applied.

    1. python manage.py makemigrations blog
    2. python manage.py migrate

In essence, after these actions, the database will be working, and the data will be saved. But you may need additional steps to adjust the database.

Database cleanup and adjustment

Depending on where and how the transferred data model was used. You may need some actions. For example, the adjustment Content Type for GenericForeignKey .

I had the simplest case - this is deleting the old Content Type . To do this, you need to connect to the database and delete information from all tables that can refer to the Content Type of the old model.

Such tables can be:

  • auth_user_user_permissions
  • auth_permission
  • django_content_type
  • etc. other models in which the old models could be used before the transfer

I will show the example of the old Content Type from my database.

Cleaning process

  1. Connect to the database

    1. sudo -u postgres psql
    2. \c myprojectdb

  2. Let's look at the django_content_type table to see which id's have obsolete Content Type.

    1. SELECT * FROM django_content_type;

    Table output
    1. id | app_label | model
    2. ----+------------------+-----------------------
    3. 1 | accounts | userprofile
    4. 2 | knowledge | section
    5. 3 | knowledge | article
    6. 4 | admin | logentry
    7. 5 | auth | permission
    8. 6 | auth | group
    9. 7 | auth | user
    10. 8 | contenttypes | contenttype
    11. 9 | sessions | session

  3. Having found old id we can try to delete them (For example 50 and 51)

    1. DELETE FROM django_content_type WHERE id BETWEEN 50 AND 51;

  4. If it did not work out, then you need to find where the ID data is used. The error will indicate in which tables they are involved. In my case, these were auth_permission and auth_user_user_permissions.

    1. SELECT * FROM auth_permission WHERE content_type_id BETWEEN 50 AND 51;

    Table output
    1. id | name | content_type_id | codename
    2. -----+--------------------+-----------------+----------------
    3. 154 | Can add chat | 50 | add_chat
    4. 155 | Can change chat | 50 | change_chat
    5. 156 | Can delete chat | 50 | delete_chat
    6. 157 | Can add message | 51 | add_message
    7. 158 | Can change message | 51 | change_message
    8. 159 | Can delete message | 51 | delete_message
    9. 276 | Can view Chat | 50 | view_chat
    10. 277 | Can view Message | 51 | view_message

    Next, we are looking for interesting id in auth_user_user_permissions
    1. SELECT * FROM auth_user_user_permissions WHERE permission_id=154;

    Table output
    1. id | user_id | permission_id
    2. -----+---------+---------------
    3. 102 | 2 | 154

  5. We remove from the table auth_user_user_permissions all permission for the old Content Type.

    1. DELETE FROM auth_user_user_permissions WHERE permission_id=154;

  6. We remove the permission from the auth_permission table.

    1. DELETE FROM auth_permission WHERE content_type_id BETWEEN 50 AND 51;

  7. Remove Content Types.

    1. DELETE FROM django_content_type WHERE id BETWEEN 50 AND 51;

Conclusion

In this way, you can move the data model of interest from one application to another, and you can also clean up the database from outdated content. However, it is necessary to work very carefully with the database in order not to violate its integrity.

For Django, I recommend Timeweb VDS-server .

Макар Карабасов
  • July 2, 2019, 3:45 a.m.

Дружище, ну подскажи. Совершенно не понял 7-й пункт. А именно, а что происходит с данными, которые в таблице? Или всё делалось, когда в таблице нет данных?

Дело в том, что у меня как раз похожая ситуация. Только нужно перенести три модели, в другое приложение. Понимаю, что всё начинается с одной. Но вот незадача. Все эти таблицы уже заполнены. И связь с этими данными уже достаточно прочная (по факту нужно перенесети каталог, из данных которого уже полно действующих заказов).

И вот мне не ясен такой момент. Вот была article_article. Я из META убираю строчку. Делаю makemigrations и migrate. Так и что происходит с таблицей? Она становиться новенькой, или просто переименовывается?

Я понимаю, что бэкапы и всё такое, но как-то честно сказать очково. Буду потом плясать с этим бэкапом.

Всё делалось, когда данные были в таблице. Сам очковал по полной, когда впервые так делал, раз на десять издевался над дампом на дев сервере, чтобы ничего не поломать.

Суть в том, что старая модель данных переносится в другое приложение, но с помощью db_table = 'article_article' старая таблица сохраняется.

Когда удаляется article_article то в миграции создаётся новое имя таблицы. То есть старая таблица переименовывается, а данные в ней сохраняются.

При этом в шаге 3 таблица условно была удалена из старого приложения, за счёт fake миграции. То есть информация о миграции добавилась, но при этом изменений не произошло.

А вот шаг 7 как раз переименовывает таблицу, чтобы она фактически лежала в новом приложении. Так что ДА - она переименовывается с сохранением данных.

Макар Карабасов
  • July 2, 2019, 2:56 p.m.

Ну я на свой страх и риск, ночью всё попробовал локально, а потом уже удалил таблицы базы на сервере и залил обновлённый дамп. Спасибо большое. Инструкция реально помогла. Правда пришлось поплясать с сылками на разные роуты. Но оно того стоило. Порядок в папках и в базе радует глаз.

Сам долго колупал форумы, чтобы найти полноценное решение, как это сделать и ничего не поломать.

Иногда там ещё бывают циклические зависимости - вот это реально проблема. Но в итоге тоже нашёл решение через сброс всех миграций и создание одной initial миграции и применение её через fake. Подробнее в этой статье .

bernar92
  • Nov. 9, 2021, 11:46 a.m.
  • (edited)

у меня была проблема что у меня в кубере автоматом миграция запускалась сделал так (как вариант решения, добовлял каждой миграции RunSQL):

  1. operations = [
  2. migrations.RunSQL('''
  3. ALTER TABLE IF EXISTS credits_operatorcreditapplication RENAME TO operator_creditapplication;
  4. create table credits_operatorcreditapplication();
  5.  
  6. delete from auth_group_permissions
  7. USING (select *
  8. from auth_permission
  9. join django_content_type dct on dct.id = auth_permission.content_type_id
  10. ) dct
  11. where dct.app_label='credits' and dct.model='operatorcreditapplication';
  12.  
  13. DELETE FROM auth_permission
  14. USING django_content_type
  15. where django_content_type.app_label='credits' and django_content_type.model='operatorcreditapplication';
  16.  
  17. DELETE FROM django_admin_log
  18. USING django_content_type
  19. where django_content_type.app_label='credits' and django_content_type.model='operatorcreditapplication';
  20.  
  21. DELETE FROM django_content_type WHERE app_label='credits' and model='operatorcreditapplication';
  22. '''),
  23. migrations.DeleteModel(
  24. name='OperatorCreditApplication',
  25. ),
  26. ]
  27.  
  28.  
  29.  
  30. operations = [
  31. migrations.CreateModel(
  32. name='OperatorCreditApplication',
  33. fields=[
  34. ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
  35. ('created_at', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='Время создания')),
  36. ('changed_at', models.DateTimeField(auto_now=True, db_index=True, verbose_name='Время последнего изменения'))
  37. ],
  38. options={
  39. 'verbose_name': '....',
  40. 'verbose_name_plural': '...',
  41. 'ordering': ('created_at'),
  42. },
  43. ),
  44. migrations.RunSQL('''
  45. DROP TABLE IF EXISTS scoring_operatorcreditapplication;
  46. ALTER TABLE IF EXISTS operator_creditapplication RENAME TO scoring_operatorcreditapplication;
  47. ''')
  48.  
  49. ]

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html