In Django, you can create database records using the Django ORM. Instead of
writing SQL INSERT statements manually, Django provides Python methods such as
create() and save() to insert records into a database.
INSTALLED_APPS.
A database record is a single row of data stored in a database table. For example, a Student table may contain information such as name, email, age, and course.
Name: Rahul
Email: rahul@example.com
Age: 20
Course: Python
In Django, each record is usually represented by an instance of a model.
Django ORM allows you to create database records using Python code.
Student.objects.create(
name="Rahul",
age=20
)
Django converts this operation into the appropriate database INSERT operation.
Consider the following model:
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
age = models.IntegerField()
course = models.CharField(max_length=100)
This model can be used to create Student records.
The create() method is one of the easiest ways to create a new
database record.
student = Student.objects.create(
name="Rahul",
email="rahul@example.com",
age=20,
course="Python"
)
The record is created and saved to the database immediately.
Another approach is to create a model object first and then call
save().
student = Student(
name="Rahul",
email="rahul@example.com",
age=20,
course="Python"
)
student.save()
The save() method writes the object to the database.
Both methods can create database records, but their usage is slightly different.
create() creates and saves the object in one operation.save() allows you to create and modify the object before saving.Student.objects.create(
name="Amit",
age=21
)
student = Student(
name="Amit",
age=21
)
student.save()
Before using a model in another Python file, import it.
from .models import Student
For example, inside views.py:
from django.shortcuts import render
from .models import Student
A record can be created inside a Django view.
from django.http import HttpResponse
from .models import Student
def create_student(request):
Student.objects.create(
name="Rahul",
email="rahul@example.com",
age=20,
course="Python"
)
return HttpResponse(
"Student created successfully"
)
You can store values in Python variables and use them while creating a record.
student_name = "Amit"
student_age = 21
Student.objects.create(
name=student_name,
age=student_age
)
This is useful when data comes from a form, API, or another source.
If a model field has a default value, you do not have to provide that value when creating the record.
class Student(models.Model):
name = models.CharField(max_length=100)
is_active = models.BooleanField(
default=True
)
Now you can create a student without explicitly providing
is_active.
Student.objects.create(
name="Rahul"
)
Django models can contain date fields.
from django.utils import timezone
student = Student.objects.create(
name="Rahul",
admission_date=timezone.now()
)
Django provides useful utilities for working with dates and times.
Django can automatically store the creation date of a record using
auto_now_add=True.
created_at = models.DateTimeField(
auto_now_add=True
)
When a new record is created, Django automatically sets the creation time.
You can create multiple objects in Python and save them individually.
student1 = Student(
name="Rahul",
age=20
)
student2 = Student(
name="Amit",
age=21
)
student1.save()
student2.save()
Each object is stored as a separate database record.
Django also provides bulk_create() for creating multiple objects
efficiently.
students = [
Student(name="Rahul", age=20),
Student(name="Amit", age=21),
Student(name="Priya", age=19)
]
Student.objects.bulk_create(students)
This is useful when inserting many records at once.
In real applications, users commonly enter information through an HTML form. The submitted data can then be used to create a model record.
name = request.POST.get("name")
email = request.POST.get("email")
Student.objects.create(
name=name,
email=email
)
For proper form handling and validation, Django Forms or ModelForms are usually preferred.
When processing an HTML form, you can check whether the request uses
POST.
def create_student(request):
if request.method == "POST":
name = request.POST.get("name")
Student.objects.create(
name=name
)
return HttpResponse(
"Student created"
)
A simple HTML form can collect student information.
<form method="POST">
{% csrf_token %}
<input
type="text"
name="name"
placeholder="Student Name"
>
<input
type="email"
name="email"
placeholder="Email"
>
<button type="submit">
Save
</button>
</form>
The submitted data can be processed by a Django view.
Django provides CSRF protection for POST forms.
{% csrf_token %}
The CSRF token should normally be included inside Django forms that submit POST requests.
User input should be validated before creating database records.
name = request.POST.get("name")
if name:
Student.objects.create(
name=name
)
Django Forms and ModelForms provide more structured validation for larger applications.
A model field can be configured with unique=True.
email = models.EmailField(
unique=True
)
This prevents duplicate values for that field at the database level.
Student.objects.create(
name="Rahul",
email="rahul@example.com"
)
Creating a record can fail when database constraints are violated. For example, a unique field may already contain the submitted value.
from django.db import IntegrityError
try:
Student.objects.create(
name="Rahul",
email="rahul@example.com"
)
except IntegrityError:
print("Could not create record")
In production applications, errors should be handled appropriately for the specific application.
A model can contain a ForeignKey to another model.
class Course(models.Model):
name = models.CharField(
max_length=100
)
class Student(models.Model):
name = models.CharField(
max_length=100
)
course = models.ForeignKey(
Course,
on_delete=models.CASCADE
)
You can create a student using an existing course object.
Student.objects.create(
name="Rahul",
course=course
)
The get_or_create() method attempts to find an existing object.
If it does not exist, Django creates one.
student, created = Student.objects.get_or_create(
email="rahul@example.com",
defaults={
"name": "Rahul",
"age": 20
}
)
The created value tells you whether a new record was created.
With get_or_create(), the returned boolean indicates whether the
object was newly created.
student, created = Student.objects.get_or_create(
email="rahul@example.com",
defaults={
"name": "Rahul"
}
)
if created:
print("New student created")
else:
print("Student already exists")
You can test record creation using the Django shell.
python manage.py shell
Then import the model:
from students.models import Student
Create a record:
Student.objects.create(
name="Rahul",
age=20
)
After creating a record, you can store the returned object and inspect it.
student = Student.objects.create(
name="Rahul",
age=20
)
print(student.id)
print(student.name)
print(student.age)
If the model uses an automatically generated primary key, Django assigns the ID when the record is saved.
After successfully processing a form, a view can redirect the user to another page.
from django.shortcuts import redirect
def create_student(request):
if request.method == "POST":
Student.objects.create(
name=request.POST.get("name")
)
return redirect("student_list")
Redirecting after a successful POST is commonly used to avoid accidental duplicate form submissions when a page is refreshed.
from django.shortcuts import redirect
from django.http import HttpResponse
from .models import Student
def create_student(request):
if request.method == "POST":
name = request.POST.get("name")
email = request.POST.get("email")
age = request.POST.get("age")
if name and email and age:
Student.objects.create(
name=name,
email=email,
age=age
)
return HttpResponse(
"Student created successfully"
)
return HttpResponse(
"Please enter all required fields"
)
return HttpResponse(
"Submit the student form"
)
{% csrf_token %} in POST forms.get() when multiple records may match.Django provides several useful ORM methods for creating database records.
objects.create() creates and saves a record.Model(...) creates an unsaved model object.save() saves a model object to the database.bulk_create() creates multiple records efficiently.get_or_create() retrieves or creates a record.objects.create() is a simple way to create and save a record.save() can be used after creating a model instance.bulk_create() is useful for multiple records.get_or_create() can find or create a record.Question: Which Django ORM method creates and saves a new database record in one operation?