Speed Up Writes with bulk_create and bulk_update
Saving objects one by one in a loop is a performance bottleneck. Use `bulk_create()` to insert a list of objects in a single query, and `bulk_update()` to update specific fields on existing objects efficiently.
Scenario 1: Bulk Create
Insert 5,000 records in one go.
entries = [Entry(headline=f"Post {i}") for i in range(5000)]
# Hits the DB once
Entry.objects.bulk_create(entries)
Scenario 2: Bulk Update
Update specific fields for a list of objects.
products_to_update = []
for p in Product.objects.all():
p.price = p.price * 1.1 # 10% increase
products_to_update.append(p)
# Only updates the 'price' column for all items in the list
Product.objects.bulk_update(products_to_update, ['price'])