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

前端 未结 8 1627
野的像风
野的像风 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:23

    Currently you are failing because you are adding a pk column that breaks the NOT NULL and UNIQUE requirements.

    You should split the migration into several steps, separating schema migrations and data migrations:

    • add the new column, indexed but not primary key, with a default value (ddl migration)
    • migrate the data: fill the new column with the correct value (data migration)
    • mark the new column primary key, and remove the former pk column if it has become unnecessary (ddl migration)
    0 讨论(0)
  • 2020-11-28 07:23

    I just tried this approach and it seems to work, for django 2.2.2, but only work for sqlite. Trying this method on other database such as postgres SQL but does not work.

    1. Add id=models.IntegerField() to model, makemigrations and migrate, provide a one off default like 1

    2. Use python shell to generate id for all objects in model from 1 to N

    3. remove primary_key=True from the primary key model and remove id=models.IntegerField(). Makemigration and check the migration and you should see id field will be migrate to autofield.

    It should work.

    I didn't know what i was doing with putting primary key into one of the field but if unsure how to handle primary key, I think better off letting Django to take care of it for you.

    0 讨论(0)
提交回复
热议问题