将主键字段更改为唯一字段 [英] Change Primary Key field to unique field

查看:370
本文介绍了将主键字段更改为唯一字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我设置数据库结构时,我很愚蠢,为我的学生类设置一个名为student_id的字段为primary_key = True。我只是意识到,有(罕见)的场合有必要改变所说的student_id。通过表单进行此操作时,Django会自动复制学生,这不是我想要的。



我想将primary_key = True更改为unique =真的,我想知道如何做到这一点。



我目前的计划是将一个名为id的字段添加到Student类中,应用迁移,然后去进入shell并简单地指定一个带有for循环的运行号码:

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

然后我会返回到我的models.py并将primary_key = True行改为unique = True。如何确保Django然后对待id字段,而不使用主键(即,当新学生添加到数据库时自动分配新的ID)?

解决方案

这不是一个愚蠢的指南,但希望它会指向正确的方向。



当您添加 id 字段时,请使用 AutoField 而不是 IntegerField 。当您添加新对象时, AutoField 负责增加。



一旦创建并填充该字段,您就可以可以设置 primary_key = True ,并将其从您的 student_id 中删除​​。



最终,您应该能够从模型中删除显式的 id 字段,因为Django会自动创建一个,如果您没有手动设置主键。 / p>

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)?

解决方案

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.

这篇关于将主键字段更改为唯一字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆