Change Primary Key field to unique field

耗尽温柔 提交于 2019-12-11 18:04:52

问题


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:


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.



来源:https://stackoverflow.com/questions/32275531/change-primary-key-field-to-unique-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!