[Django]-Is this the correct way of making primary keys in django?

1👍

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

6👍

The correct syntax for primary key is-:

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

2👍

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

No. You use an AutoField [Django-doc] for a primary key, since then the values are dispatched by the database, so:

class profiles(models.model):
    customer_ID = models.AutoField(primary_key=True, editable=False)

But you do not have to specify a primary key: if you do not specify one yourself, Django will add one with the name id to the model automatically.

Leave a comment