python / intermediate
Snippet
Batch Record Modifications using Django bulk_update on Specific Fields
Calling .save() inside a loop triggers a separate SQL query for every single database row, creating severe performance bottlenecks. bulk_update efficiently updates multiple model instances in a single SQL operation, allowing developers to restrict updates strictly to designated fields and chunk execution with batch_size.
snippet.py
python
1
2
3
4
5
6
from myapp.models import Productdef discount_products(product_list, discount_rate):for product in product_list:product.price = product.price * (1 - discount_rate)Product.objects.bulk_update(product_list, ['price'], batch_size=500)
django
Breakdown
1
for product in product_list:
Iterates through the collection of existing product model instances in memory.
2
product.price = product.price * (1 - discount_rate)
Updates the target attribute value locally on each model instance.
3
Product.objects.bulk_update(product_list, ['price'], batch_size=500)
Executes an optimized SQL UPDATE statement in batches of 500 targeting only the 'price' column.