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().

Django Delete Data – Interview Questions

Q 1: How do you delete a record in Django?
Ans: Using the delete() method.
Q 2: Can multiple records be deleted at once?
Ans: Yes, using queryset delete().
Q 3: Is delete reversible?
Ans: No, unless custom logic is used.
Q 4: Can admin panel delete records?
Ans: Yes.
Q 5: What is soft delete?
Ans: Marking records inactive instead of deleting.

Django Delete Data– Objective Questions (MCQs)

Q1. To delete a single object in Django, which method is used?






Q2. Which method is used to fetch an object before deleting it?






Q3. To delete multiple objects at once, which statement is correct?






Q4. The delete() method returns:






Q5. Deleting data using Django ORM protects against:






Related Django Delete DataTopics