primary key django model

In Django, a primary key is a unique identifier for each record in a database table. It is used to uniquely identify each row in the table.

To define a primary key in a Django model, follow these steps:

  1. First, import the necessary modules:
from django.db import models
  1. Next, create a class for your model and subclass it from models.Model:
class MyModel(models.Model):
    pass
  1. Then, define the fields of your model. To define a primary key, you can use the models.AutoField field. This field automatically increments the value of the primary key for each new record:
class MyModel(models.Model):
    id = models.AutoField(primary_key=True)
  1. You can also use other field types as primary keys, such as models.IntegerField or models.UUIDField. For example, to use an IntegerField as the primary key:
class MyModel(models.Model):
    id = models.IntegerField(primary_key=True)
  1. Finally, run database migrations to apply the changes to the database schema. This step is necessary whenever you make changes to your models:
python manage.py makemigrations
python manage.py migrate

By following these steps, you can define a primary key in a Django model and ensure that each record in the corresponding database table has a unique identifier.