Delete Multiple Objects at Once in Django
Last Updated :
04 Nov, 2024
In Django, deletions of objects are very common once we want to delete outdated information or information we no longer have a need for within our database. Django ORM provides several and efficient ways to delete models instances.
To delete instances in Django, we can use either of the following methods:
- ModelInstance.delete() - To delete a single object.
- Queryset.delete() - To delete multiple instances.
- Using Raw SQl Query
In this article, we will learn how to use Django's built-in methods to delete single and many objects at once.
For the demonstration purpose, we will use the following models:
models.py
Python
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
price = models.FloatField(default=100)
is_in_stock = models.BooleanField(default=True)
def __str__(self) -> str:
return self.name
class Author(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
def __str__(self):
return self.title
Using QuerySet.delete() Method:
Django provides a method called delete() that can be applied to a QuerySet. This allows us to delete multiple objects with a single command, which can be more efficient than deleting them one by one.
Python
from myapp.models import Product
q = Product.objects.filter(is_in_stock=False)
print(q)
# <QuerySet [<Product: Laptop>, <Product: Smartwatch>]>
q.delete()
# (2, {'myapp.Product': 2})
Explanation: Product.objects.filter(is_in_stock=False) retrieves a QuerySet containing all objects which are not in stock and the delete() method deletes all objects in the QuerySet in one go.
Deleting Multiple Objects by Primary Keys (IDs)
In cases where we know the primary keys (IDs) of the objects we want to delete, Django allows us to filter objects by their primary key using the in lookup.
Python
from myapp.models import delete
# List of IDs of the objects to delete
ids_to_delete = [2, 5]
q = Product.objects.filter(id__in=ids_to_delete)
print(q)
# <QuerySet [<Product: Smartphone>, <Product: Tablet>]>
q.delete()
# (2, {'myapp.Product': 2})
Explanation: id__in=ids_to_delete filters objects where the id field is in the list ids_to_delete. The delete() method deletes all matching objects.
Django models support the concept of foreign key relationships. When we delete a parent object, we might also want to delete all the related objects. This can be done automatically by using on_delete=models.CASCADE in our model definition.
Here, we will delete Author instance and Book instances related to that Author, will be automatically deleted.
Python
from myapp.models import Book, Author
author = Author.objects.get(name="GFG")
print(author)
# <Author: GFG>
author.book_set.all()
# <QuerySet [<Book: Learn Django>, <Book: Learn Python>, <Book: Learn Flask>]>
author.delete()
# (4, {'myapp.Book': 3, 'myapp.Author': 1})
The output (4, {'myapp.Book': 3, 'myapp.Author': 1}) indicates that 4 total objects were deleted: 1 Author and 3 Book objects related to the author. Django handles cascading deletions automatically when the foreign key is set to on_delete=models.CASCADE.
Using Raw SQL for Bulk Deletion
For advanced use cases, we can directly execute raw SQL queries using Django’s raw() method or connection API. This is not recommended unless necessary.
Python
from myapp.models import Product
from django.db import connection
Product.objects.filter(is_in_stock=False)
# <QuerySet [<Product: Smartwatch>, <Product: Laptop>]>
with connection.cursor() as cursor:
cursor.execute("DELETE FROM myapp_product WHERE is_in_stock='0'")
rows_deleted = cursor.rowcount
print(rows_deleted)
# Output: 2
Explanation:
- Here, with connection.cursor() as cursor: creates a database cursor object using with statement. The cursor allows executing raw SQL queries against the database. The cursor.execute() method is used to run the provided SQL query.
- DELETE FROM myapp_product WHERE is_in_stock='0' - This query deletes all rows from the myapp_product table where is_in_stock='0' (meaning the products are out of stock).
Similar Reads
Working with Multiple Databases in Django Django stands out as a powerful and versatile framework for building dynamic and scalable applications. One of its notable features is its robust support for database management, offering developers flexibility in choosing and integrating various database systems into their projects. In this article
3 min read
How to Add Multiple Objects to ManyToMany Relationship at Once in Django? In Django, the ManyToManyField allows for the creation of relationships where multiple records in one table can be associated with multiple records in another table. Adding multiple objects to a Many-to-Many relationship is a common requirement in web development, especially when dealing with things
3 min read
How to combine multiple QuerySets in Django? QuerySets allow you to filter, order, and manipulate data from your database using a high-level Pythonic syntax. However, there are situations where you may need to combine multiple QuerySets into a single QuerySet to work with the data more efficiently. This article will explore various methods to
5 min read
How to Efficiently Delete a Record in Django In Django, deleting a record (or row) from a database table associated with a model is straightforward. Django models provide a delete() method that can be called on an individual object, or on a QuerySet of objects to remove them from the database. Deleting records is a fundamental operation, often
9 min read
Delete View - Function based Views Django Delete View refers to a view (logic) to delete a particular instance of a table from the database. It is used to delete entries in the database for example, deleting an article at geeksforgeeks. So Delete view must show a confirmation message to the user and should delete the instance automatically.
3 min read