Django Delete Data

In Django, deleting data from the database involves removing records (rows) from the corresponding table. The Django ORM provides methods like .delete() to handle this easily, either for a single record or multiple records.

Delete a Single Record

You retrieve the record you want to delete and call the .delete() method on it.


from myapp.models import Book  # Replace 'myapp' with your app name

# Retrieve a book by its ID
book = Book.objects.get(id=1)

# Delete the record
book.delete()

Explanation:

1) get(id=1) fetches the book with the primary key (ID) 1.

2) .delete() removes this record from the database.

Delete Multiple Records

If you want to delete multiple records, use the .filter() method to select the records and call .delete() on the queryset.

Example:


from myapp.models import Book

# Delete all books published before 2000
Book.objects.filter(published_year__lt=2000).delete()

Explanation:

1. filter(published_year__lt=2000) selects all books published before the year 2000.

2. .delete() removes all matching records.

Delete All Records in a Table

To delete all records from a table (be cautious as this cannot be undone):

Example:


from myapp.models import Book

# Delete all records in the Book table
Book.objects.all().delete()

Summary

Delete a single record: Use get() and .delete().

Delete multiple records: Use filter() and .delete().

Delete all records: Use all() and .delete().

Deletions are permanent and immediate, so always double-check before running .delete().