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.
delete().
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.
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.
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.
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.
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")
You can call delete() directly on a QuerySet.
Student.objects.filter(
id=5
).delete()
This deletes all records matching the filter condition.
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.
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.
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.
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.
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.
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()
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.
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.
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>
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>
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
}
)
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.
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.
You can delete records that match a specific condition.
Student.objects.filter(
course="Old Course"
).delete()
All records matching the condition are deleted.
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.
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.
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.
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.
| 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 |
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()
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
}
)
<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>
delete() on the wrong object.filter() condition accidentally.
Django ORM provides the delete() method for removing existing
database records.
object.delete().queryset.delete().filter() can be used to select records before deletion.get_object_or_404() is useful in delete views.on_delete behavior.delete() removes an existing database record.get_object_or_404() is useful for delete views.on_delete controls behavior for related objects.Question: Which Django ORM method is used to remove an existing database record?