Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing django default pk with AutoField to 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)

a model referencing Student

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")
    )
like image 808
Festus Fashola Avatar asked Jun 30 '17 06:06

Festus Fashola


People also ask

What is Django DB models BigAutoField?

BigAutoField is a 64-bit integer, much like an AutoField except that it is guaranteed to fit numbers from 1 to 9223372036854775807. One can create a BigAutoField using the following syntax, id = models.BigAutoField(primary_key=True, **options)

What is Default_auto_field?

default_auto_field attribute. No more needing to override primary keys in all models. Maintaining the historical behavior, the default value for DEFAULT_AUTO_FIELD is AutoField . Starting with 3.2 new projects are generated with DEFAULT_AUTO_FIELD set to BigAutoField . Also, new apps are generated with AppConfig.


1 Answers

Set primary_key=True in the field definition:

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

And in your other models:

class SomeModel(BigPkAbstract):
    <your model here>

like image 103
The_Cthulhu_Kid Avatar answered Sep 21 '22 13:09

The_Cthulhu_Kid