Update all elements in the current QuerySet, setting all the given fields to the appropriate values.
(self, **kwargs)
| 1358 | _raw_delete.alters_data = True |
| 1359 | |
| 1360 | def update(self, **kwargs): |
| 1361 | """ |
| 1362 | Update all elements in the current QuerySet, setting all the given |
| 1363 | fields to the appropriate values. |
| 1364 | """ |
| 1365 | self._not_support_combined_queries("update") |
| 1366 | if self.query.is_sliced: |
| 1367 | raise TypeError("Cannot update a query once a slice has been taken.") |
| 1368 | if self.query.distinct_fields: |
| 1369 | raise TypeError("Cannot call update() after .distinct(*fields).") |
| 1370 | self._for_write = True |
| 1371 | query = self.query.chain(sql.UpdateQuery) |
| 1372 | query.add_update_values(kwargs) |
| 1373 | |
| 1374 | # Inline annotations in order_by(), if possible. |
| 1375 | new_order_by = [] |
| 1376 | for col in query.order_by: |
| 1377 | alias = col |
| 1378 | descending = False |
| 1379 | if isinstance(alias, str) and alias.startswith("-"): |
| 1380 | alias = alias.removeprefix("-") |
| 1381 | descending = True |
| 1382 | if annotation := query.annotations.get(alias): |
| 1383 | if getattr(annotation, "contains_aggregate", False): |
| 1384 | raise exceptions.FieldError( |
| 1385 | f"Cannot update when ordering by an aggregate: {annotation}" |
| 1386 | ) |
| 1387 | if descending: |
| 1388 | annotation = annotation.desc() |
| 1389 | new_order_by.append(annotation) |
| 1390 | else: |
| 1391 | new_order_by.append(col) |
| 1392 | query.order_by = tuple(new_order_by) |
| 1393 | |
| 1394 | # Clear SELECT clause as all annotation references were inlined by |
| 1395 | # add_update_values() already. |
| 1396 | query.clear_select_clause() |
| 1397 | with transaction.mark_for_rollback_on_error(using=self.db): |
| 1398 | rows = query.get_compiler(self.db).execute_sql(ROW_COUNT) |
| 1399 | self._result_cache = None |
| 1400 | return rows |
| 1401 | |
| 1402 | update.alters_data = True |
| 1403 |
no test coverage detected