Skip to content

Commit 5351fe9

Browse files
committed
Add documentation regarding bulk upserts
1 parent ad336d1 commit 5351fe9

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

docs/manager.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,49 @@ This is also known as a "upsert".
170170

171171
This is preferable when the data you're about to insert is the same as the one that already exists. This is more performant because it avoids a write in case the row already exists.
172172

173+
### Bulk
174+
`bulk_insert` allows your to use conflict resolution for bulk inserts:
175+
176+
from django.db import models
177+
from psqlextra.models import PostgresModel
178+
179+
class MyModel(PostgresModel):
180+
name = models.CharField(max_length=255, unique=True)
181+
182+
obj = (
183+
MyModel.objects
184+
.on_conflict(['name'], ConflictAction.UPDATE)
185+
.bulk_insert([
186+
dict(name='swen'),
187+
dict(name='henk'),
188+
dict(name='adela')
189+
])
190+
)
191+
192+
`bulk_insert` uses a single query to insert all specified rows at once.
193+
194+
#### Limitations
195+
In order to stick to the "everything in one query" principle, various, more advanced usages of `bulk_insert` are impossible. It is not possible to have different rows specify different amounts of columns. The following example does **not work**:
196+
197+
from django.db import models
198+
from psqlextra.models import PostgresModel
199+
200+
class MyModel(PostgresModel):
201+
first_name = models.CharField(max_length=255, unique=True)
202+
last_name = models.CharField(max_length=255, default='kooij')
203+
204+
obj = (
205+
MyModel.objects
206+
.on_conflict(['name'], ConflictAction.UPDATE)
207+
.bulk_insert([
208+
dict(name='swen'),
209+
dict(name='henk', last_name='poepjes'), # invalid, different column configuration
210+
dict(name='adela')
211+
])
212+
)
213+
214+
An exception is thrown if `django-postgres-extra` detects this behavior.
215+
173216
### Shorthand
174217
The `on_conflict`, `insert` and `insert_or_create` methods were only added in `django-postgres-extra` 1.6. Before that, only `ConflictAction.UPDATE` was supported in the following form:
175218

0 commit comments

Comments
 (0)