我的模型有一个带有AutoField(整数)的默认pk,但后来发现我需要使用BigAutoField代替! 此外我还有其他模型参考学生模型的数据::如何将pk字段更改为BigAutoField并反映其他参考模型
class Student(models.Model):
matric_no = models.CharField(max_length=20, unique=True) # first set it to U(random)
password = models.CharField(max_length=128)
session = models.ForeignKey(Session, null=True)
programme = models.ForeignKey(Programme, null=True)
school = models.ForeignKey(School, null=True)
course_comb = models.ForeignKey(CourseComb, null=True)
serial = models.IntegerField(null=True)
current_level = models.CharField(max_length=3, choices=LEVEL_CHOICES, default='100', null=True)
last_login = models.DateField(null=True)
is_active = models.CharField(max_length=1, default=1, choices=((1, 1), (0, 0)))
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
引用学生的模型
class Profile(models.Model):
student = models.OneToOneField(Student, on_delete=models.CASCADE)
attachment = models.ImageField(null=True, blank=True, verbose_name="Profile Image")
surname = models.CharField(max_length=255, null=True, verbose_name="Surname")
othernames = models.CharField(max_length=255, null=True, verbose_name="Othernames")
SEX_CHOICES = (
("M", "Male"),
("F", "Female")
)
答案 0 :(得分:4)
在字段定义中设置primary_key=True
:
id = models.BigAutoField(primary_key=True)
如果你想在多个模型中使用它,你也可以制作一个抽象模型,让别人继承它:
class BigPkAbastract(models.Model):
id = models.BigAutoField(primary_key=True)
class Meta:
abstract = True
在你的其他模特中:
class SomeModel(BigPkAbastract):
<your model here>