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

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

    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.

提交回复
热议问题