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

Django, Application, Model

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 to . 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

    class Meta:
          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.

    python makemigrations blog
      python makemigrations article

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

    python 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.

    python makemigrations blog
      python 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

    sudo -u postgres psql
      \c myprojectdb

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

    SELECT * FROM django_content_type;
    Table output
    id |    app_label     |         model         
       1 | accounts         | userprofile
       2 | knowledge        | section
       3 | knowledge        | article
       4 | admin            | logentry
       5 | auth             | permission
       6 | auth             | group
       7 | auth             | user
       8 | contenttypes     | contenttype
       9 | sessions         | session

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

    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.

    SELECT * FROM auth_permission WHERE content_type_id BETWEEN 50 AND 51;
    Table output
    id  |        name        | content_type_id |    codename    
      154 | Can add chat       |              50 | add_chat
      155 | Can change chat    |              50 | change_chat
      156 | Can delete chat    |              50 | delete_chat
      157 | Can add message    |              51 | add_message
      158 | Can change message |              51 | change_message
      159 | Can delete message |              51 | delete_message
      276 | Can view Chat      |              50 | view_chat
      277 | Can view Message   |              51 | view_message
    Next, we are looking for interesting id in auth_user_user_permissions
    SELECT * FROM auth_user_user_permissions WHERE permission_id=154;
    Table output
    id  | user_id | permission_id
      102 |       2 |           154

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

    DELETE FROM auth_user_user_permissions WHERE permission_id=154;

  6. We remove the permission from the auth_permission table.

    DELETE FROM auth_permission WHERE content_type_id BETWEEN 50 AND 51;

  7. Remove Content Types.

    DELETE FROM django_content_type WHERE id BETWEEN 50 AND 51;


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 .

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate


Only authorized users can post comments.
Please, Log in or Sign up
May 19, 2019, 1:49 a.m.

Qt - Test 001. Signals and slots

  • Result:78points,
  • Rating points2
May 17, 2019, 1:14 p.m.

Qt - Test 001. Signals and slots

  • Result:42points,
  • Rating points-8
May 17, 2019, 4:18 a.m.

C++ - Тест 003. Условия и циклы

  • Result:57points,
  • Rating points-2
Last comments
May 20, 2019, 7:20 p.m.
Евгений Легоцкой

Добрый день! Вы не думали разместить репозиторий проекта на GitHub?
May 18, 2019, 2:03 p.m.

Спасибо большое! Вскоре буду разбираться!
May 18, 2019, 9:13 a.m.
Евгений Легоцкой

Добрый день! Отнимать значение общего счётчика можно в деструкторе класса кнопки QDynamicButton::~QDynamicButton(){ ResID--;} При этом я бы ещё переустанавливал значения вс...
May 14, 2019, 10:33 p.m.

Здравствуйте!А не подскажите, как можно при удалении какой либо кнопки, у щётчика отнять значение?Дабы например четвёртой кнопке соответствовал ID 4, а не 5 скажем
May 6, 2019, 6:39 a.m.
Евгений Легоцкой

Добрый день. Этот урок для Qt Quick Control версии 1, Вы используете вторую версию. Здесь style уже нет, кастомизацию можно делать уже или черещ соответствующие property или через ...
Now discuss on the forum
May 21, 2019, 1:38 p.m.

Всем доброго времени суток. Прошу помощи у сообщества, как начинающий программист. Есть задача реализовать динамическую библиотеку на Qt5.12.3. Поискав на просторах Интернета нашел немал...
May 20, 2019, 8:43 a.m.

Кинул библиотеки в папку с проектом и в папку к компилируемым файлам.В файле проекта прописал так, но все равно выдает ту же ошибку QT += core gui networkgreaterThan(QT_MAJOR_VERSI...
May 20, 2019, 1:47 a.m.

Что вы понимаете под статической сборкой приложений? В какой среде?
May 19, 2019, 10:52 a.m.
Евгений Легоцкой

Если честно, то мне нужно самому время потратить, чтобы глянуть это дело. Я использовал Flutter для разработки, а не Qt. Просто исходя из опыта, могу сказать, что по большей части всё на эмуля...
May 16, 2019, 11:08 p.m.

Решил через indexOf сделать. Возвращает или номер позиции где нашел символ или строку или -1 если не найдено.

For registered users on the site there is a minimum amount of advertising

Join us
© EVILEG 2015-2019
Recommend hosting TIMEWEB