Lesson 33 of 60 – Updating Records in Django
55%

Updating Records in Django

Updating records means changing existing data stored in the database. Django ORM provides simple methods such as save() and update() for modifying existing records.

Note: Before updating a record, you normally retrieve the object or QuerySet that you want to change and then save the new values.

1. What is Updating a Record?

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.

2. Example Student 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
    )

    is_active = models.BooleanField(
        default=True
    )

We will use this model throughout the examples in this lesson.

3. Updating a Record with save()

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.

4. Updating Multiple Fields

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.

5. Updating with update()

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.

6. Updating Multiple Records

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.

7. save() vs update()

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
)

8. Updating a Record by ID

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.

9. Updating a Record Safely

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")

10. Using get_object_or_404()

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()

11. Updating a Boolean Field

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.

12. Updating Text Fields

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()

13. Updating Numeric Fields

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.

14. Updating with filter()

You can combine filter() and update().

Student.objects.filter(
    course="Python"
).update(
    course="Django"
)

All matching records are updated.

15. Updating Using Multiple Conditions

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.

16. update() Return Value

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.

17. Updating from an HTML Form

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>

18. Processing an Update 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"
        )

19. Using POST for Updates

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.

Important: Do not remove CSRF protection simply to avoid a CSRF error. Configure and use the form correctly.

20. Updating Through a URL Parameter

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
    )

21. Updating a Date Field

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.

22. update_fields with save()

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.

23. Updating with F Expressions

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.

24. Updating Records with get_or_create()

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()

25. Updating Records in Django Shell

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()

26. Updating and Redirecting

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.

27. Complete Update View

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
        }
    )

28. Updating Multiple Records

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.

29. Common Mistakes While Updating Records

  • Forgetting to call save() after changing a model object.
  • Using the wrong record ID.
  • Updating records without a proper filter() condition.
  • Using update() when instance-level behavior is required.
  • Not validating form input.
  • Forgetting {% csrf_token %} in POST forms.
  • Not handling a missing record.
  • Using incorrect model field names.
  • Accidentally updating multiple records.
  • Not redirecting after a successful form submission when appropriate.

30. Summary of Updating Records

Django provides several ways to update existing database records.

  • Retrieve an object and modify it using save().
  • Use 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.
  • POST requests are commonly used for update forms.
  • CSRF protection should be maintained.
  • Validate user input before saving changes.
  • Always make sure your QuerySet targets the intended records.

📌 Key Points

  • 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.
  • Multiple fields can be changed before calling 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.
  • POST forms should include CSRF protection.
  • Always validate user input and carefully check update conditions.

🧠 Quick Quiz

Question: Which Django ORM method can update multiple records matching a QuerySet condition?