Renaming an app with Django and South

前端 未结 6 771
栀梦
栀梦 2020-12-13 02:28

I am renaming an application to a more suitable name. In doing so, I want to ensure that South properly migrates the database (renames database tables and changes reference

6条回答
  •  伪装坚强ぢ
    2020-12-13 02:47

    Disclaimer: this isn't probably the ideal way to do it, but this is definitely easier than a lot of other approaches suggested elsewhere/earlier.

    If you're using PyCharm you can try the following solution.

    • right click on the app directory in your Django project
    • Refactor > Rename > Enter new app name (new_app)
    • Check both Search for references and Search in comments and strings, Scope Project Files > Refactor
    • This would show you where the files would be renamed > Refactor
    • If you are not happy with your Project name, you can do the same for the Project name as well

    Now comes the problem.

    python manage.py makemigrations

    python manage.py migrate

    What would this do?

    • This would basically create a new app and apply all the migrations to this new app
    • However, your data still resides in the old app (old_app)
    • We need to bring that to the new_app tables

    In your DB, we need to

    1. insert the data into the new_app tables by copying it from the old_app tables

    INSERT INTO new_app_table_name SELECT * FROM old_app_table_name;

    You have to do this for all the models/tables in your app

    1. Reset the sequence of the tables to avoid getting the primary key violation error in django

    SELECT setval('new_app_table_name_id_seq', (SELECT MAX(id) FROM new_app_table_name));

    You have to do this for all the tables from Step 1.

    I don't want to be ignorant and claim that it should be as easy as this. My project and model structure were fairly complicated but this worked like charm for me. However, if your project structure is too complicated only parts of this might work for you.

    There are only two hard things in Computer Science: cache invalidation and naming things.

    -- Phil Karlton

提交回复
热议问题