Opened 7 years ago
Closed 7 years ago
#29037 closed New feature (duplicate)
Add a bulk_update method to models
Reported by: | Tom Forbes | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | dev |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description (last modified by )
Currently it's not easily or neatly possible to update multiple rows with differing values using the ORM. Most people who need to update a number of models with a value that's distinct to each model need to issue N queries. This is akin to the situation that lead to the addition of bulk_create.
Updating multiple rows with differing values in a single query is indeed possible in SQL, and Postgres has some specific syntax for it[1]. Other databases can use a CASE/WHEN:
SomeModel.object.filter(id__in=[1,2]).update( some_field=Case( When(id=1, then=Value('Field value for ID=1')), When(id=2, then=Value('Field value for ID=2')) ) )
This isn't particularly elegant and cannot take advantage of specific DB features (like pg UPDATE FROM), and batching is hard. An API similar to bulk_create would be nice:
SomeModel.objects.bulk_update(list_of_models, batch_size=100, fields=['some_field'])
There is some prior art in the django-bulk-update package[2], which has some impressive performance numbers in it's readme.
Change History (5)
comment:1 by , 7 years ago
Description: | modified (diff) |
---|
comment:2 by , 7 years ago
Description: | modified (diff) |
---|
comment:3 by , 7 years ago
comment:4 by , 7 years ago
Has patch: | set |
---|
PR: https://github.com/django/django/pull/9606