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

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

    I would like to share my case: The column email was the primary key, but now that's wrong. I need to change the primary key to another column. After trying some suggestions, I finally came up with the most simple solution:

    1. First, drop the old primary key. This step requires custom the migrations a bit:
    • edit the model to replace primary_key=True on email column by blank=True, null=True
    • run makemigrations to create a new migration file and edit it like this:
    class Migration(migrations.Migration):
    
        dependencies = [
            ('api', '0026_auto_20200619_0808'),
        ]
        operations = [
            migrations.RunSQL("ALTER TABLE api_youth DROP CONSTRAINT api_youth_pkey"),
            migrations.AlterField(
                model_name='youth', name='email',
                field=models.CharField(blank=True, max_length=200, null=True))
        ]
    
    
    • run migrate
    1. Now your table has no primary key, you can add a new column or user an old column to be a primary key. Just change the model then migrate. Do some extra script if you need a new column to fill and make sure it includes unique values only.

提交回复
热议问题