How to use bulk_update() in Django?

Hi Dev,
Are you looking to learn how to use bulk_update() in Django? You're in the right place! In this comprehensive tutorial, we’ll explore how to update multiple records efficiently using Django's bulk_update()
method.
This guide will walk you through a practical and beginner-friendly example of Django bulk_update(), helping you understand how to perform bulk updates with minimal database hits.
bulk_update() in Django is a powerful ORM method that allows you to update specific fields on a set of model instances in a single query—improving your app's performance and reducing query load.
Below, we provide a step-by-step example on how to implement and use bulk_update() in your Django project effectively.
Syntax:
bulk_update(objs, fields, batch_size=None)
Step 1: Create a Project
In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:
django-admin startproject example
Step 2: Create a App
Now we'll create a single app called core to store a list of post names and store bulk of data in database. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.
python3 manage.py startapp core
Step 3: Update setting.py
In this step we require to do add installed apps in our settings.py file. Add the below lines to your settings.py file:
Next, you need to add it in the settings.py file as follows:
settings.py.... INSTALLED_APPS = [ ….. 'core' ]
Step 4: Create a Model
In this step now go for the models we will We'll call our single model Post and it will have just two fields: title and content. And finally set __str__ to display the name of the post.
core/models.pyfrom django.db import models class Post(models.Model): title = models.CharField(max_length=250) content = models.TextField() def __str__(self): return self.title
Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.
python manage.py makemigrations python manage.py migrate
Step 5: Update admin.py File
In this step the Post class of the models is registered using the register() method to display the books tables in the Django administration dashboard.
core/admin.pyImport admin module from django.contrib import admin # Import Post model from .models import Post # Register Post model admin.site.register(Post)
Step 6: Creating the Views
In this step, we need to create the views for performing fetch record to the database.Open the core/views.py file and add:
core/views.pyfrom django.shortcuts import render from django.views.generic import ListView from .models import Post # Create your views here. class BulkUpdate(ListView): model = Post template_name = 'postlist.html' queryset = Post.objects.all() if queryset.exists() == True: update_queries = [] a = Post.objects.get(id=1) b = Post.objects.get(id=2) c = Post.objects.get(id=3) #set update value a.title="Hello django updated" b.title="Hello python updated" c.title="Hello php updated" #append update_queries.extend((a, b, c)) Post.objects.bulk_update(update_queries, ['title']) def get_queryset(self): return Post.objects.all()
Step 7: Creating the Templates
Next, then with your text editor create new templates files: core/templates/postlist.html file and the add:
core/templates/postlist.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Tuts-Station.com</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"> <style type="text/css"> body{ background-color: #f7fcff; } </style> </head> <body> <div class="container mt-5 pt-5"> <div class="row d-flex justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header"> <h5>How to use bulk_update() in Django App? - <span class="text-primary"></span>Tuts-Station.com</h5> </div> <div class="card-body"> <table class="table table-bordered"> <thead> <tr> <th>Title</th> <th>Content</th> </tr> </thead> <tbody> {% for post in object_list %} <tr> <td>{{ post.title }}</td> <td>{{ post.content }}</td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> </div> </body> </html>
Step 8: Creating URLs
In this section, we’ll create the urls to access our CRUD views.Go to the urls.py core/urls.py file and update it as follows:
core/urls.pyfrom django.urls import path from core import views urlpatterns = [ path('post/', views.BulkUpdate.as_view()), ]
Next, we will require the modify the urls.py your root preoject folder lets update the file.
example/urls.pyfrom django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls')), ]
Run the Server
In this step, we’ll run the local development server for playing with our app without deploying it to the web.
python manage.py runserver
Next, go to the http://localhost:8000/post/ address with a web browser.
I Hope It will help you....
Happy Pythonic Coding!!