primary_key — Django inline field validation

Note : primary_key = True means null = False and unique = True . Only one primary key is allowed per object.


 field_name = models.Field (primary_key = True) 

Django built-in field validation primary_key = True Explanation

Illustration of primary_key = True using example. Consider a project named pythonengineering that has an application named geeks .

Refer to the following articles to check how to create a project and an app in Django.

Enter the following code into the models.py file of the geeks application. We`ll use IntegerField to experiment with the primary_key.

from django.db import models

from django.db.models import Model

# Create your models here.


class GeeksModel (Model):

geeks_field = models.IntegerField (primary_key = True )

After starting As for the makemigrations and migrations to Django and the rendering of the above model, let`s try creating an instance using None from the Django shell. To start the Django shell, enter the command,

 Python manage.py shell 

Now let`s try to create a GeeksModel instance using None .

# import required model

from geeks. models import GeeksModel

# instantiate GeeksModel

s = GeeksModel.objects.create (geeks_field = 12 )

# save the current instance of the model
s.save ()  

Let`s check in the admin interface if the model is instantiated. 

Therefore, primary_key = True changes the field to the PRIMARY KEY for this table. To learn more about the Primary Key,

Get Solution for free from DataCamp guru