Skip to content
Advertisement

Is this the correct way of making primary keys in django?

class profiles(models.model):
    customer_ID = models.IntegerField().primary_key

Is this the correct way of making a primary key in django??

Advertisement

Answer

No, That is not the correct way of making a primary key in Django, in fact you don’t have to specify a Primary key for your model, because django will automatically add a field to hold the primary key for you.

In your settings.py file, you will find a line with:

DEFAULT_AUTO_FIELD = ‘django.db.models.BigAutoField’

which will automatically creates an ‘id’ field in all of your models by default. The BigAutoField is a 64bit integer that automatically increments according to available ids from 1 to 9223372036854775807.

class Profile(models.Model):

    customer_username = models.CharField(max_length=100)
    customer_email = models.EmailField()

the Profile model will have three fields: id, customer_username, customer_email

but, in case you want to overide the primary key, let’s say for instane by using UUIDs instead of regular ids, you can overide it as follows:

import uuid

class Profile(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4,editable=False)
    customer_username = models.CharField(max_length=100)
    customer_email = models.EmailField()

for more details, please refer to the django documentation: https://docs.djangoproject.com/en/4.0/ref/models/fields/#primary-key

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement