What is the best approach to change primary keys in an existing Django app?

前端 未结 8 1624
野的像风
野的像风 2020-11-28 06:23

I have an application which is in BETA mode. The model of this app has some classes with an explicit primary_key. As a consequence Django use the fields and doesn\'t create

8条回答
  •  無奈伤痛
    2020-11-28 07:05

    I had the same problem to day and came to a solution inspired by the answers above.

    My model has a "Location" table. It has a CharField called "unique_id" and I foolishly made it a primary key, last year. Of course they didn't turn out to be as unique as expected at the time. There is also a "ScheduledMeasurement" model that has a foreign key to "Location".

    Now I want to correct that mistake and give Location an ordinary auto-incrementing primary key.

    Steps taken:

    1. Create a CharField ScheduledMeasurement.temp_location_unique_id and a model TempLocation, and migrations to create them. TempLocation has the structure I want Location to have.

    2. Create a data migration that sets all the temp_location_unique_id's using the foreign key, and that copies over all the data from Location to TempLocation

    3. Remove the foreign key and the Location table with a migration

    4. Re-create the Location model the way I want it to be, re-create the foreign key with null=True. Renamed 'unique_id' to 'location_code'...

    5. Create a data migration that fills in the data in Location using TempLocation, and fills in the foreign keys in ScheduledMeasurement using temp_location

    6. Remove temp_location, TempLocation and null=True in the foreign key

    And edit all the code that assumed unique_id was unique (all the objects.get(unique_id=...) stuff), and that used unique_id otherwise...

提交回复
热议问题