Change Primary Key field to unique field

2019-09-07 20:54发布

When setting up my database structure, I was stupid enough to set a field called "student_id" as "primary_key=True" for my Student class. I only realised much later that there are (rare) occasions where it is necessary to change said "student_id". When doing that via a form, Django will automatically duplicate the student, which is not what I want.

I would like to change "primary_key=True" to "unique=True", and am wondering how to do that.

My current plan is to add a field called "id" to the Student class, apply the migrations, and to go into the shell and simply assign it a running number with a for loop:

counter = 0
for s in Student.objects.all():
    counter += 1
    s.id = counter
    s.save()

I would then go back into my models.py and change the line "primary_key=True" to "unique=True". How do I make sure that Django then treats the "id" field as it would with classes without a primary key (ie automatically assign a new ID when a new student is added to the database)?

1条回答
\"骚年 ilove
2楼-- · 2019-09-07 21:19

This isn't a foolproof guide, but hopefully it will point you in the right direction.

When you add the id field, use an AutoField instead of an IntegerField. The AutoField takes care of incrementing when you add new objects.

Once the field has been created and populated, you can set primary_key=True, and remove it from your student_id.

Eventually, you should be able to remove the explicit id field from your model, since Django automatically creates one if you don't set a primary key manually.

查看更多
登录 后发表回答