Updating records means changing existing data stored in the database.
Django ORM provides simple methods such as save() and
update() for modifying existing records.
Updating a record means changing one or more values of an existing database row.
For example, a student's age may change from 20 to 21.
Before:
Name: Rahul
Age: 20
After:
Name: Rahul
Age: 21
Django ORM allows this operation using Python code.
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
)
is_active = models.BooleanField(
default=True
)
We will use this model throughout the examples in this lesson.
The most common approach is to retrieve an object, change its field, and call
save().
student = Student.objects.get(
id=1
)
student.age = 21
student.save()
The updated value is then stored in the database.
You can change multiple fields before calling save().
student = Student.objects.get(
id=1
)
student.name = "Amit"
student.age = 22
student.course = "Django"
student.save()
All changed fields are saved when save() is called.
The update() method can update one or more records represented by
a QuerySet.
Student.objects.filter(
id=1
).update(
age=21
)
This directly updates the matching database record.
One important advantage of update() is that it can modify many
records at once.
Student.objects.filter(
is_active=True
).update(
course="Python"
)
Every matching active student will have the course changed to Python.
Both methods can update database records, but they are used differently.
save() works with a model instance.update() works with a QuerySet.update() is useful for updating multiple matching records.save() is useful when you need to work with an individual object.student = Student.objects.get(id=1)
student.age = 21
student.save()
Student.objects.filter(
age=20
).update(
age=21
)
A common update operation is to find a record using its primary key.
student = Student.objects.get(
id=5
)
student.name = "Rahul Kumar"
student.save()
Only the record with ID 5 is modified.
When using get(), the record may not exist. You can handle the
exception.
try:
student = Student.objects.get(
id=5
)
student.age = 22
student.save()
except Student.DoesNotExist:
print("Student not found")
Django provides get_object_or_404() for views where a missing
object should result in a 404 response.
from django.shortcuts import (
get_object_or_404
)
student = get_object_or_404(
Student,
id=5
)
student.name = "Rahul Kumar"
student.save()
Boolean fields can also be updated easily.
student = Student.objects.get(
id=1
)
student.is_active = False
student.save()
This can be useful for activating or deactivating records.
Text fields can be changed by assigning a new value.
student = Student.objects.get(
id=1
)
student.name = "Amit Kumar"
student.course = "Python"
student.save()
Numeric fields can be updated by assigning a new number.
student = Student.objects.get(
id=1
)
student.age = 25
student.save()
Django converts the Python value into the appropriate database value.
You can combine filter() and update().
Student.objects.filter(
course="Python"
).update(
course="Django"
)
All matching records are updated.
Multiple conditions can be used before updating records.
Student.objects.filter(
age__gte=18,
is_active=True
).update(
course="Django"
)
Only active students aged 18 or older are updated.
The update() method returns the number of rows matched and
updated by the query.
updated = Student.objects.filter(
course="Python"
).update(
course="Django"
)
print(updated)
The returned number can be used to check how many records were affected.
A common application pattern is to display existing data in a form and allow the user to modify it.
<form method="POST">
{% csrf_token %}
<input
type="text"
name="name"
value="{{ student.name }}"
>
<input
type="email"
name="email"
value="{{ student.email }}"
>
<button type="submit">
Update
</button>
</form>
The view can retrieve the record and update it when the request method is
POST.
def update_student(request, id):
student = get_object_or_404(
Student,
id=id
)
if request.method == "POST":
student.name = request.POST.get(
"name"
)
student.email = request.POST.get(
"email"
)
student.save()
return redirect(
"student_list"
)
HTML forms that modify database data commonly use the POST method.
<form method="POST">
{% csrf_token %}
...
</form>
The CSRF token should be included in Django POST forms.
A record ID can be passed through a URL to identify which record should be updated.
path(
"student/update/<int:id>/",
views.update_student,
name="update_student"
)
The ID is received by the view.
def update_student(request, id):
student = get_object_or_404(
Student,
id=id
)
Date and DateTime fields can also be changed.
from django.utils import timezone
student = Student.objects.get(
id=1
)
student.updated_at = timezone.now()
student.save()
Django provides utilities for working with timezone-aware dates and times.
The save() method can receive update_fields when you
want to specify which fields should be saved.
student = Student.objects.get(
id=1
)
student.name = "Rahul Kumar"
student.age = 22
student.save(
update_fields=[
"name",
"age"
]
)
This tells Django which fields to include in the update.
Django's F() expressions allow database fields to be updated
based on their current values.
from django.db.models import F
Student.objects.filter(
id=1
).update(
age=F("age") + 1
)
This increases the existing age value by one.
get_or_create() is mainly used to retrieve an existing object or
create it when it does not exist. If an object already exists, you can update
it separately.
student, created = Student.objects.get_or_create(
email="rahul@example.com",
defaults={
"name": "Rahul",
"age": 20
}
)
if not created:
student.age = 21
student.save()
The Django shell can be used to practice update operations.
python manage.py shell
Import the model:
from students.models import Student
Retrieve and update a record:
student = Student.objects.get(id=1)
student.age = 22
student.save()
After successfully updating a record through a form, the user can be redirected to another page.
from django.shortcuts import redirect
student.name = request.POST.get(
"name"
)
student.save()
return redirect(
"student_list"
)
This creates a clean workflow after the update operation.
from django.shortcuts import (
render,
redirect,
get_object_or_404
)
from .models import Student
def update_student(request, id):
student = get_object_or_404(
Student,
id=id
)
if request.method == "POST":
student.name = request.POST.get(
"name"
)
student.email = request.POST.get(
"email"
)
student.age = request.POST.get(
"age"
)
student.course = request.POST.get(
"course"
)
student.save()
return redirect(
"student_list"
)
return render(
request,
"students/update.html",
{
"student": student
}
)
The update() method is especially useful when the same change
needs to be applied to many records.
updated = Student.objects.filter(
course="HTML"
).update(
course="Web Development"
)
print(
"Updated records:",
updated
)
Always make sure the filter condition selects the records you intend to change.
save() after changing a model object.filter() condition.update() when instance-level behavior is required.{% csrf_token %} in POST forms.Django provides several ways to update existing database records.
save().update() to update records represented by a QuerySet.update() can modify multiple matching records.update_fields can specify fields to save with save().F() expressions can perform database-side field calculations.get_object_or_404() is useful for update views.save() updates an individual model instance.update() updates records in a QuerySet.filter() can be used to select records before updating them.get_object_or_404() is useful when updating a record by ID.save().update() can update multiple records at once.update_fields can limit which fields are saved.F() expressions can update values based on their current database values.Question: Which Django ORM method can update multiple records matching a QuerySet condition?