本文介绍了将带有AutoField的Django默认pk更改为BigAutoField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型具有默认的pk,其中包含AutoField(整数),但后来我发现我需要改用BigAutoField!然后我还有其他模型引用学生模型的数据::如何将pk字段更改为BigAutoField并在其他引用模型上进行反思

My model has a default pk with AutoField (integer) but later on i discovered that i need to use BigAutoField instead! And also i have data in then with other models referencing the student model:: how do i change the pk field to BigAutoField and also reflects on other referencing models

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

推荐答案

在字段定义中设置 primary_key = True :

id = models.BigAutoField(primary_key=True)

如果要在多个模型中使用此模型,还可以创建一个抽象模型并让其他人继承它:

If you want to use this in multiple models you could also make an abstract model and let others inherit it:

class BigPkAbstract(models.Model):
    id = models.BigAutoField(primary_key=True)
    
    class Meta:
        abstract = True

在其他型号中:

class SomeModel(BigPkAbstract):
    <your model here>

这篇关于将带有AutoField的Django默认pk更改为BigAutoField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 16:22