Django Delete Data

Removing records from your database

🗑️ What is Deleting Data?

Deleting data means removing records from your database permanently. Django provides simple methods to delete single records or multiple records at once using model instances or querysets.


# Delete a product
product = Product.objects.get(id=1)
product.delete()
                                    

Key Delete Methods

Delete Single

Remove one record

obj.delete()
🗑️

Delete Multiple

Remove many records at once

Model.objects.filter().delete()
⚠️

Cascade Delete

Delete related records too

on_delete=models.CASCADE
🔒

Protect Delete

Prevent deletion if related

on_delete=models.PROTECT

🔹 Delete a Single Record

Retrieve a record and delete it from the database. This is the most common way to delete individual records safely.

# models.py
from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    stock = models.IntegerField()

# Get and delete a product
product = Product.objects.get(id=1)
product_name = product.name
product.delete()

print(f"Deleted product: {product_name}")

Output:

Deleted product: Laptop

🔹 Delete Multiple Records

Use filter() with delete() to remove multiple records at once:

# Delete all products with stock = 0
deleted_count, _ = Product.objects.filter(stock=0).delete()
print(f"Deleted {deleted_count} out-of-stock products")

# Delete products cheaper than $10
deleted_count, _ = Product.objects.filter(price__lt=10).delete()
print(f"Deleted {deleted_count} cheap products")

# Delete all products in a category
deleted_count, _ = Product.objects.filter(category='old').delete()
print(f"Deleted {deleted_count} old category products")

Output:

Deleted 3 out-of-stock products

Deleted 5 cheap products

Deleted 8 old category products

🔹 Delete All Records

Delete all records from a table (use with caution!):

# Delete ALL products (be careful!)
deleted_count, _ = Product.objects.all().delete()
print(f"Deleted all {deleted_count} products")

# Better: Delete with confirmation
if confirm_deletion:
    Product.objects.all().delete()
    print("All products deleted")

Output:

Deleted all 25 products

⚠️ Warning:

Deleting all records is permanent! Always add confirmation before using this in production.

🔹 Safe Delete with get_object_or_404

Use get_object_or_404 to handle missing records gracefully:

from django.shortcuts import get_object_or_404

# Safe delete - returns 404 if not found
def delete_product(request, product_id):
    product = get_object_or_404(Product, id=product_id)
    product_name = product.name
    product.delete()
    
    print(f"Successfully deleted: {product_name}")
    return redirect('product_list')

Output:

Successfully deleted: Mouse

🔹 Cascade Delete with Relationships

When you delete a record, related records can be deleted automatically:

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(
        Author, 
        on_delete=models.CASCADE  # Delete books when author is deleted
    )

# Delete author - all their books are deleted too
author = Author.objects.get(id=1)
author.delete()  # This also deletes all books by this author

print(f"Deleted author and all their books")

Output:

Deleted author and all their books

🔹 Delete Protection

Prevent deletion if related records exist:

from django.db import models
from django.db.models import PROTECT

class Category(models.Model):
    name = models.CharField(max_length=100)

class Product(models.Model):
    name = models.CharField(max_length=100)
    category = models.ForeignKey(
        Category,
        on_delete=models.PROTECT  # Prevent category deletion if products exist
    )

# Try to delete category with products
try:
    category = Category.objects.get(id=1)
    category.delete()
except models.ProtectedError:
    print("Cannot delete: Products exist in this category")

Output:

Cannot delete: Products exist in this category

🔹 Delete from Views

Handle deletion in Django views with confirmation:

# views.py
from django.shortcuts import render, redirect, get_object_or_404
from .models import Product

def delete_product(request, product_id):
    product = get_object_or_404(Product, id=product_id)
    
    if request.method == 'POST':
        product_name = product.name
        product.delete()
        return redirect('product_list')
    
    return render(request, 'confirm_delete.html', {'product': product})
<!-- templates/confirm_delete.html -->
<h2>Confirm Deletion</h2>
<p>Are you sure you want to delete "{{ product.name }}"?</p>

<form method="post">
    {% csrf_token %}
    <button type="submit">Yes, Delete</button>
    <a href="{% url 'product_list' %}">Cancel</a>
</form>

🔹 Other Delete Options

Different behaviors when deleting related records:

from django.db import models

class Product(models.Model):
    category = models.ForeignKey(
        Category,
        on_delete=models.CASCADE  # Delete product when category deleted
    )

class Product(models.Model):
    category = models.ForeignKey(
        Category,
        on_delete=models.SET_NULL,  # Set to NULL when category deleted
        null=True
    )

class Product(models.Model):
    category = models.ForeignKey(
        Category,
        on_delete=models.SET_DEFAULT,  # Set to default when category deleted
        default=1
    )

🧠 Test Your Knowledge

Which method deletes a single record?