Deleting Model Instances
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.
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.
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.
result = Book.objects.filter(pages__lt=50).delete()
print(result)
⚠️ Run this command in your terminal.
- Calling .delete() on a whole unfiltered QuerySet by accident, wiping out every row in the table.
- Forgetting that deleting an object can cascade and delete related objects too, depending on on_delete settings.
- Not confirming the object exists before calling .delete(), risking a DoesNotExist error.
- 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.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: