Охватываемые темы: bulk_create — Mass Creation, bulk_update — Mass Update, update() — Queryset-Level Update, delete() — Queryset-Level Deletion.
bulk_create — Mass Creation
tasks = [
Task(title='Task 1', status='todo'),
Task(title='Task 2', status='todo'),
Task(title='Task 3', status='in_progress'),
]
Task.objects.bulk_create(tasks)
# One SQL INSERT instead of three
bulk_update — Mass Update
tasks = Task.objects.filter(status='todo')
for task in tasks:
task.priority = 5
Task.objects.bulk_update(tasks, ['priority'])
# One SQL UPDATE instead of N
update() — Queryset-Level Update
# Update the status of all overdue tasks
Task.objects.filter(due_date__lt=today, status='todo').update(status='overdue')
delete() — Queryset-Level Deletion
# Delete all completed tasks older than 30 days
Task.objects.filter(status='done', updated_at__lt=threshold).delete()
Performance Comparison
| Method | 1000 objects | SQL queries |
|---|---|---|
Loop save() |
slow | 1000 |
bulk_create() |
fast | 1 |
update() |
very fast | 1 |
Limitations of bulk_create
- Does not call
save()or signals - Does not update
auto_nowfields by default - Supports
update_conflicts=Truefor PostgreSQL
Task.objects.bulk_create(
tasks,
update_conflicts=True,
unique_fields=['title'],
update_fields=['status', 'priority'],
)
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!