Change language

BigAutoField Django Models

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)

This is an auto-incrementing primary key just like AutoField.

Django Model BigAutoField Explanation

Illustration of BigAutoField using an Example. Consider a project named geeksforgeeks having an app named geeks.

from django.db import models
from django.db.models import Model
# Create your models here.

class GeeksModel(Model):
	big_id = models.BigAutoField(primary_key = True)

Add the geeks app to INSTALLED_APPS

# Application definition

INSTALLED_APPS = [
	’django.contrib.admin’,
	’django.contrib.auth’,
	’django.contrib.contenttypes’,
	’django.contrib.sessions’,
	’django.contrib.messages’,
	’django.contrib.staticfiles’,
	’geeks’,
]

Now when we run makemigrations command from the terminal,

Python manage.py makemigrations

A new folder named migrations would be created in geeks directory with a file named 0001_initial.py

# Generated by Django 2.2.5 on 2019-09-25 06:00

from django.db import migrations, models

class Migration(migrations.Migration):

	initial = True

	dependencies = [
	]

	operations = [
		migrations.CreateModel(
			name =’GeeksModel’,
			fields =[
				(’big_id’,
				models.BigAutoField(auto_created = True,
				primary_key = True,
				serialize = False,
				verbose_name =’ID’
				)),
			],
		),
	]

Therefore, a big_id BigAutoField that automatically increments on each instance of that model is created when you run makemigrations on the project. It is a primary key for the table created for the model named GeeksModel.

Possible errors

Since a Django model can have at most one autofield, BigAutoField must be created on the first migration with the primary_key attribute = True, otherwise it will generate multiple errors.

"AssertionError: A model cannot have more than one AutoField."

If you get this error, try deleting recent migrations and adding primary_key = True to the field. Run migrations again to resolve the issue.

If we create objects of this empty model from the admin server. we can see the auto-increment of the id field on each instance created.

Field options

Field options are the arguments given to each field to apply some restriction or convey a particular feature to a particular field. For example, adding a primary_key = True argument to BigAutoField will make it the primary key for that table in a relational database.

Here are the options and attributes a BigAutofield can use.

Field OptionsDescription
NullIf True, Django will store empty values as NULL in the database. Default is False.
BlankIf True, the field is allowed to be blank. Default is False.
db_indexIf True, a database index will be created for this field.
db_tablespaceThe name of the database tablespace to use for this field’s index if this field is indexed. The default is the project’s DEFAULT_INDEX_TABLESPACE setting, if set, or the db_tablespace of the model if any. If the backend doesn’t support tablespaces for indexes, this option is ignored.
db_columnThe name of the database column to use for this field. If this isn’t given, Django will use the field’s name. 
 
DefaultThe default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created. 
 
help_textExtra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form. 
 
primary_keyIf True, this field is the primary key for the model.
editableIf False, the field will not be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True
 
error_messagesThe error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override. 
 
help_textExtra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form. 
 
verbose_nameA human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces. 
 
validatorsA list of validators to run for this field. See the validators documentation for more information. 
 
UniqueIf True, this field must be unique throughout the table. 
 

Upgrading to Django 3.2 and fixing DEFAULT_AUTO_FIELD warnings

When you define a model in Django without specifying a primary key, Django automatically creates a primary key for you. The primary key is set to an integer. If you want to override the field type, you can do so based on the template.

Since Django 3.2, you can now customize the type of primary key that is automatically created in your settings.

When starting new projects in Django 3.2, the default type for primary keys is set to BigAutoField which is a 64-bit integer. However, previous versions defined the type of implicit primary keys to integers.

This means that when you upgrade to 3.2, you will start to see warnings that you do not have an explicitly defined primary key type. Satisfying Django’s requirements for an explicitly defined primary key type is fairly straightforward, but you also have to choose whether or not you want to update the primary key field types from integer to a 64-bit integer.

After updating to 3.2, the suggestion in the official documents is to run

python -Wa manage.py test

Changing django default pk with AutoField to BigAutoField

StackOverflow question

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

Answer:

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>

Shop

Gifts for programmers

Best laptop for Excel

$
Gifts for programmers

Best laptop for Solidworks

$399+
Gifts for programmers

Best laptop for Roblox

$399+
Gifts for programmers

Best laptop for development

$499+
Gifts for programmers

Best laptop for Cricut Maker

$299+
Gifts for programmers

Best laptop for hacking

$890
Gifts for programmers

Best laptop for Machine Learning

$699+
Gifts for programmers

Raspberry Pi robot kit

$150

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

1947 answers

PythonStackOverflow

Check if one list is a subset of another in Python

1173 answers

PythonStackOverflow

How to specify multiple return types using type-hints

1002 answers

PythonStackOverflow

Printing words vertically in Python

909 answers

PythonStackOverflow

Python Extract words from a given string

798 answers

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

606 answers

PythonStackOverflow

Python os.path.join () method

384 answers

PythonStackOverflow

Flake8: Ignore specific warning for entire file

360 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically