Performs bulk update in one database session to speed up the process. Allows you to update multiple instance at once. All `Models` passed need to have primary key column populated. You can also select which fields to update by passing `columns` list as a l
( # noqa: CCR001
self, objects: list["T"], columns: Optional[list[str]] = None
)
| 1395 | obj.set_save_status(True) |
| 1396 | |
| 1397 | async def bulk_update( # noqa: CCR001 |
| 1398 | self, objects: list["T"], columns: Optional[list[str]] = None |
| 1399 | ) -> None: |
| 1400 | """ |
| 1401 | Performs bulk update in one database session to speed up the process. |
| 1402 | |
| 1403 | Allows you to update multiple instance at once. |
| 1404 | |
| 1405 | All `Models` passed need to have primary key column populated. |
| 1406 | |
| 1407 | You can also select which fields to update by passing `columns` list |
| 1408 | as a list of string names. |
| 1409 | |
| 1410 | Bulk operations do not send signals. |
| 1411 | |
| 1412 | :param objects: list of ormar models |
| 1413 | :type objects: list[Model] |
| 1414 | :param columns: list of columns to update |
| 1415 | :type columns: list[str] |
| 1416 | """ |
| 1417 | if not objects: |
| 1418 | raise ModelListEmptyError("Bulk update objects are empty!") |
| 1419 | |
| 1420 | ready_objects = [] |
| 1421 | pk_name = self.model_config.pkname |
| 1422 | if not columns: |
| 1423 | columns = list( |
| 1424 | self.model.extract_db_own_fields().union( |
| 1425 | self.model.extract_related_names() |
| 1426 | ) |
| 1427 | ) |
| 1428 | |
| 1429 | if pk_name not in columns: |
| 1430 | columns.append(pk_name) |
| 1431 | |
| 1432 | onupdate_fields = self.model._onupdate_fields |
| 1433 | for field_name in onupdate_fields: |
| 1434 | if field_name not in columns: |
| 1435 | columns.append(field_name) |
| 1436 | |
| 1437 | columns = [self.model.get_column_alias(k) for k in columns] |
| 1438 | |
| 1439 | for i, obj in enumerate(objects): |
| 1440 | explicit_fields = obj.__setattr_fields__ |
| 1441 | new_kwargs = obj.model_dump() |
| 1442 | if new_kwargs.get(pk_name) is None: |
| 1443 | raise ModelPersistenceError( |
| 1444 | "You cannot update unsaved objects. " |
| 1445 | f"{self.model.__name__} has to have {pk_name} filled." |
| 1446 | ) |
| 1447 | new_kwargs = obj.populate_onupdate_value( |
| 1448 | new_kwargs, explicit_fields=explicit_fields |
| 1449 | ) |
| 1450 | obj.update_from_dict( |
| 1451 | { |
| 1452 | field_name: new_kwargs[field_name] |
| 1453 | for field_name in onupdate_fields - explicit_fields |
| 1454 | } |