← Back to Django Course | Chapter 4: Models & Django ORM Basics | Lesson 9 of 10

Deleting Model Instances

Deleting is like taking a card out of the filing cabinet and shredding it — it's gone from the database for good.

Deleting a Single Object

Fetch the object first, then call .delete() on that instance to remove just that one row from the database.

Example: Deleting a Single Object

Fetch the object first, then call .delete() on that instance to remove just that one row from the database.

bash
book = Book.objects.get(id=1)
book.delete()

⚠️ Run this command in your terminal.

Deleting Multiple Objects

Calling .delete() directly on a filtered QuerySet removes every row that matches the filter, all in one database operation.

Warning: Always filter carefully before calling .delete() — Book.objects.all().delete() removes every row in the table.

Example: Deleting Multiple Objects

Calling .delete() directly on a filtered QuerySet removes every row that matches the filter, all in one database operation.

bash
Book.objects.filter(genre='Horror').delete()

⚠️ Run this command in your terminal.

Confirming Deletion

.delete() returns a tuple with the total number of objects deleted, which is useful for confirming what actually happened.

Example: Confirming Deletion

.delete() returns a tuple with the total number of objects deleted, which is useful for confirming what actually happened.

bash
result = Book.objects.filter(pages__lt=50).delete()
print(result)

⚠️ Run this command in your terminal.

Common Mistakes
  1. Calling .delete() on a whole unfiltered QuerySet by accident, wiping out every row in the table.
  2. Forgetting that deleting an object can cascade and delete related objects too, depending on on_delete settings.
  3. Not confirming the object exists before calling .delete(), risking a DoesNotExist error.
Chapter Summary
  • Calling .delete() on a single fetched instance removes just that row.
  • Calling .delete() on a filtered QuerySet removes every matching row at once.
  • Deletion is permanent — Django does not keep a built-in undo or trash bin.
  • Related objects can be deleted automatically depending on the on_delete rule set on a ForeignKey.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.