Bulk Update with bulk_update()

A snippet showing how to update multiple records efficiently with bulk_update().


# models.py

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=120)
    price = models.DecimalField(max_digits=8, decimal_places=2, default=0.00)
    in_stock = models.BooleanField(default=True)

    def __str__(self):
        return f"{self.name} - ${self.price}"
  

# views.py

from django.http import HttpResponse
from .models import Product

def restock_and_reprice(request):
    products = list(Product.objects.filter(in_stock=False)[:200])
    for p in products:
        p.in_stock = True
        p.price = p.price * 1.05
    Product.objects.bulk_update(products, ['in_stock', 'price'], batch_size=500)
    return HttpResponse("Updated stock and price.")
  
Explanation:
  • bulk_update() updates many rows efficiently with a single SQL statement per table.
  • Pass a list of model instances and the list of fields to update; only those fields are written to the DB.
  • Use batch_size for very large updates to manage memory and DB load.
  • Signals (pre_save/post_save) don't fire for bulk operations; handle side effects manually if needed.
  • Category Models & ORM
  • Total Views 1261
  • Last Modified 03 December, 2025
  • Tags #bulk #update #orm #models
Next snippet
Model Meta Options
Never miss a story on Django.wiki

Subscribe for fresh tutorials, snippets, and updates.

By subscribing you agree to our Privacy Policy.