| 8 | |
| 9 | Like this: |
| 10 | {{{ |
| 11 | diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py |
| 12 | --- a/django/db/models/sql/compiler.py |
| 13 | +++ b/django/db/models/sql/compiler.py |
| 14 | @@ -1230,11 +1230,11 @@ class SQLInsertCompiler(SQLCompiler): |
| 15 | else: |
| 16 | result.append("VALUES (%s)" % ", ".join(placeholder_rows[0])) |
| 17 | params = [param_rows[0]] |
| 18 | - col = "%s.%s" % (qn(opts.db_table), qn(opts.pk.column)) |
| 19 | r_fmt, r_params = self.connection.ops.return_insert_id() |
| 20 | # Skip empty r_fmt to allow subclasses to customize behavior for |
| 21 | # 3rd party backends. Refs #19096. |
| 22 | if r_fmt: |
| 23 | + col = "%s.%s" % (qn(opts.db_table), qn(opts.pk.column)) |
| 24 | result.append(r_fmt % col) |
| 25 | params += [r_params] |
| 26 | return [(" ".join(result), tuple(chain.from_iterable(params)))] |
| 27 | @@ -1341,6 +1341,9 @@ class SQLUpdateCompiler(SQLCompiler): |
| 28 | where, params = self.compile(self.query.where) |
| 29 | if where: |
| 30 | result.append('WHERE %s' % where) |
| 31 | + if self.connection.features.can_return_ids_from_bulk_insert: |
| 32 | + opts = self.query.get_meta() |
| 33 | + result.append("RETURNING %s.%s" % (qn(opts.db_table), qn(opts.pk.column))) |
| 34 | return ' '.join(result), tuple(update_params + params) |
| 35 | |
| 36 | def execute_sql(self, result_type): |
| 37 | @@ -1352,6 +1355,8 @@ class SQLUpdateCompiler(SQLCompiler): |
| 38 | """ |
| 39 | cursor = super().execute_sql(result_type) |
| 40 | try: |
| 41 | + if self.connection.features.can_return_ids_from_bulk_insert: # for Postgresql return the |
| 42 | + return self.connection.ops.fetch_returned_insert_ids(cursor) # PKs of the matched columns |
| 43 | rows = cursor.rowcount if cursor else 0 |
| 44 | is_empty = cursor is None |
| 45 | finally: |
| 46 | diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt |
| 47 | --- a/docs/ref/models/querysets.txt |
| 48 | +++ b/docs/ref/models/querysets.txt |
| 49 | @@ -2241,7 +2241,8 @@ retrieves the results and then checks if any were returned. |
| 50 | |
| 51 | Performs an SQL update query for the specified fields, and returns |
| 52 | the number of rows matched (which may not be equal to the number of rows |
| 53 | -updated if some rows already have the new value). |
| 54 | +updated if some rows already have the new value). On Postgresql it returns |
| 55 | +instead a list with the primary keys of the matched rows. |
| 56 | |
| 57 | For example, to turn comments off for all blog entries published in 2010, |
| 58 | you could do this:: |
| 59 | }}} |