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:
- First, import the necessary modules:
from django.db import models
- Next, create a class for your model and subclass it from
models.Model
:
class MyModel(models.Model):
pass
- 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)
- You can also use other field types as primary keys, such as
models.IntegerField
ormodels.UUIDField
. For example, to use anIntegerField
as the primary key:
class MyModel(models.Model):
id = models.IntegerField(primary_key=True)
- 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.