Bulk Create with bulk_create()
A snippet showing how to insert multiple records efficiently with bulk_create().
# 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)
def __str__(self):
return self.name
# views.py
from django.shortcuts import HttpResponse
from .models import Product
def seed_products(request):
items = [
Product(name=f"Item {i}", price=10 + i)
for i in range(1, 6)
]
Product.objects.bulk_create(items, batch_size=1000)
return HttpResponse("Seeded products.")
# views.py (conflict-safe insert)
from django.db import transaction
from .models import Product
def safe_seed(request):
items = [Product(name="Unique A", price=5), Product(name="Unique B", price=7)]
with transaction.atomic():
Product.objects.bulk_create(items, ignore_conflicts=True)
return HttpResponse("Done.")
Explanation:
-
bulk_create()inserts many rows in a single query, which is far faster than calling.save()in a loop. -
Use
batch_sizeto split very large inserts into manageable chunks for your DB backend. -
ignore_conflicts=Trueskips rows that violate unique constraints instead of raising errors. - Auto fields may not be populated on returned objects across all backends; re-query if you need generated IDs.
- Category Models & ORM
- Total Views 1181
- Last Modified 08 November, 2025
- Tags #bulk #create #orm #models
Previous snippet
Using prefetch_related for Optimization
Next snippet