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
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read