Lesson 34 of 60 – Deleting Records in Django
57%

Deleting Records in Django

Deleting records means removing existing data from the database. Django ORM provides the delete() method to remove individual objects or multiple records from a QuerySet.

Warning: Deleting a record is usually permanent. Always make sure that you are deleting the correct record or QuerySet before calling delete().

1. What is Deleting a Record?

Deleting a record means removing an existing row from a database table.

Before:

ID    Name
1     Rahul
2     Amit
3     Priya

After deleting ID 2:

ID    Name
1     Rahul
3     Priya

Django ORM allows you to perform this operation using Python.

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 for the deletion examples.

3. The delete() Method

Django models provide the delete() method for removing an existing object.

student = Student.objects.get(
    id=1
)

student.delete()

The student with ID 1 is removed from the database.

4. Deleting by ID

A common way to delete one record is to retrieve it using its ID and then call delete().

student = Student.objects.get(
    id=5
)

student.delete()

Only the object with ID 5 is targeted.

5. Handling DoesNotExist

The get() method raises DoesNotExist if the requested record is not found.

try:

    student = Student.objects.get(
        id=100
    )

    student.delete()

except Student.DoesNotExist:

    print("Student not found")

6. Deleting with filter()

You can call delete() directly on a QuerySet.

Student.objects.filter(
    id=5
).delete()

This deletes all records matching the filter condition.

7. Deleting Multiple Records

A QuerySet can match multiple records. Calling delete() on that QuerySet can remove all matching records.

Student.objects.filter(
    is_active=False
).delete()

This deletes all students whose is_active value is false.

8. Deleting with Multiple Conditions

You can use multiple conditions before deleting records.

Student.objects.filter(
    age__lt=18,
    is_active=False
).delete()

Only records matching both conditions are selected for deletion.

9. Checking Before Delete

For important data, it is often useful to inspect or count the records before deleting them.

students = Student.objects.filter(
    is_active=False
)

print(
    students.count()
)

You can review the QuerySet before performing the deletion.

10. Using exists() Before Delete

The exists() method can check whether matching records are available.

students = Student.objects.filter(
    id=5
)

if students.exists():

    students.delete()

This can be useful when your application needs to perform an action only if a matching record exists.

11. Delete View Using ID

A Django view can receive an ID and delete the corresponding record.

def delete_student(request, id):

    student = Student.objects.get(
        id=id
    )

    student.delete()

In a real application, the view should also handle missing records and authorize the deletion appropriately.

12. Using get_object_or_404()

Django provides get_object_or_404() for retrieving an object or returning a 404 response if it does not exist.

from django.shortcuts import (
    get_object_or_404
)

student = get_object_or_404(
    Student,
    id=id
)

student.delete()

13. Redirecting After Delete

After deleting a record, you can redirect the user to another page.

from django.shortcuts import (
    redirect
)

student.delete()

return redirect(
    "student_list"
)

This is commonly used after deleting a record from a management page.

14. Delete URL Pattern

The ID of the record can be passed through a URL.

path(
    "student/delete/<int:id>/",
    views.delete_student,
    name="delete_student"
)

The URL parameter is received by the view as id.

15. Delete Button in Template

A template can provide a link or button that points to a delete URL.

<a
    href="{% url 'delete_student' student.id %}"
    class="btn btn-danger"
>
    Delete
</a>
Important: For destructive actions, applications commonly use a confirmation step and an appropriate HTTP method rather than blindly performing deletion from a simple GET link.

16. Delete Confirmation

A confirmation step can help prevent accidental deletion.

<form method="POST">

    {% csrf_token %}

    <p>
        Are you sure you want to delete
        {{ student.name }}?
    </p>

    <button
        type="submit"
        class="btn btn-danger"
    >
        Yes, Delete
    </button>

</form>

17. Processing a POST Delete

A safer pattern is to perform the destructive action when the confirmation form submits a POST request.

def delete_student(request, id):

    student = get_object_or_404(
        Student,
        id=id
    )

    if request.method == "POST":

        student.delete()

        return redirect(
            "student_list"
        )

    return render(
        request,
        "students/delete.html",
        {
            "student": student
        }
    )

18. Why Use POST for Delete?

Deleting data changes the server-side state of the application. A POST form is commonly used for destructive actions so that simply visiting a URL does not perform the deletion.

  • GET is normally used for retrieving information.
  • POST is commonly used for operations that change data.
  • CSRF protection should be used with Django POST forms.
  • A confirmation page can reduce accidental deletion.

19. Delete Form with CSRF

A Django delete confirmation form should include the CSRF token.

<form method="POST">

    {% csrf_token %}

    <button
        type="submit"
        class="btn btn-danger"
    >
        Delete Student
    </button>

</form>

The CSRF token helps protect the POST request against cross-site request forgery.

20. Deleting Records with a Condition

You can delete records that match a specific condition.

Student.objects.filter(
    course="Old Course"
).delete()

All records matching the condition are deleted.

Warning: Carefully check the filter condition before deleting multiple records.

21. Delete Return Value

The delete() method returns information about how many objects were deleted and details of deletion by model.

result = Student.objects.filter(
    is_active=False
).delete()

print(result)

The returned value is useful when you need to know whether records were actually removed.

22. Cascade Deletion

When models have relationships, deleting an object can affect related objects depending on the on_delete behavior configured on the relationship.

class Student(models.Model):

    course = models.ForeignKey(
        Course,
        on_delete=models.CASCADE
    )

With CASCADE, deleting the referenced Course can cause related Student objects to be deleted according to Django's relationship behavior.

23. Protecting Related Records

Sometimes you do not want a related object to be deleted while dependent records exist. Django provides options such as PROTECT.

course = models.ForeignKey(
    Course,
    on_delete=models.PROTECT
)

With PROTECT, deleting the referenced object is prevented when protected related objects exist.

24. Soft Delete Concept

A soft delete does not actually remove the database row. Instead, the application marks the record as deleted or inactive.

Student.objects.filter(
    id=1
).update(
    is_active=False
)

The record remains in the database and can potentially be restored later.

25. Hard Delete vs Soft Delete

Hard Delete Soft Delete
Removes the record Keeps the record
Usually cannot be restored directly Can potentially be restored
Uses delete() Often uses a status field
Useful when data should be permanently removed Useful when records need historical retention

26. Deleting from Django Shell

You can practice deletion operations from the Django shell.

python manage.py shell

Import the model:

from students.models import Student

Retrieve and delete a record:

student = Student.objects.get(
    id=1
)

student.delete()

27. Complete Delete View

from django.shortcuts import (
    render,
    redirect,
    get_object_or_404
)

from .models import Student


def delete_student(request, id):

    student = get_object_or_404(
        Student,
        id=id
    )

    if request.method == "POST":

        student.delete()

        return redirect(
            "student_list"
        )

    return render(
        request,
        "students/delete.html",
        {
            "student": student
        }
    )

28. Complete Delete Template

<h2>
    Delete Student
</h2>

<p>
    Are you sure you want to delete
    {{ student.name }}?
</p>

<form method="POST">

    {% csrf_token %}

    <button
        type="submit"
        class="btn btn-danger"
    >
        Yes, Delete
    </button>

    <a
        href="{% url 'student_list' %}"
        class="btn btn-secondary"
    >
        Cancel
    </a>

</form>

29. Common Mistakes While Deleting Records

  • Calling delete() on the wrong object.
  • Using a broad filter() condition accidentally.
  • Deleting multiple records without checking the QuerySet.
  • Not handling a missing record.
  • Performing destructive actions through unsafe GET requests.
  • Forgetting CSRF protection on POST forms.
  • Ignoring relationships and cascade behavior.
  • Deleting important data without a recovery strategy.
  • Not providing a confirmation step for important deletions.

30. Summary of Deleting Records

Django ORM provides the delete() method for removing existing database records.

  • A model instance can be deleted using object.delete().
  • A QuerySet can be deleted using queryset.delete().
  • filter() can be used to select records before deletion.
  • get_object_or_404() is useful in delete views.
  • POST is commonly used for destructive form actions.
  • CSRF protection should be maintained for POST requests.
  • Confirmation pages can reduce accidental deletion.
  • Related records can be affected by on_delete behavior.
  • Soft delete can be used when records should remain in the database.
  • Always verify the records selected for deletion.

📌 Key Points

  • delete() removes an existing database record.
  • A model instance can be deleted directly.
  • A QuerySet can delete multiple matching records.
  • Always check the filter condition before deleting multiple records.
  • get_object_or_404() is useful for delete views.
  • POST requests are commonly used for destructive operations.
  • CSRF protection should be used with Django POST forms.
  • on_delete controls behavior for related objects.
  • Soft delete can preserve records instead of permanently removing them.
  • Deletion should be handled carefully because it can remove important data.

🧠 Quick Quiz

Question: Which Django ORM method is used to remove an existing database record?