Bulk insert operation: .. note:: The bulk insert operation will do the minimum to ensure that the object created in the DB has all the defaults and generated fields set, but may be incomplete reference in Python. e.g. ``IntField`` pr
(
cls: type[MODEL],
objects: Iterable[MODEL],
batch_size: int | None = None,
ignore_conflicts: bool = False,
update_fields: Iterable[str] | None = None,
on_conflict: Iterable[str] | None = None,
using_db: BaseDBAsyncClient | None = None,
)
| 1436 | |
| 1437 | @classmethod |
| 1438 | def bulk_create( |
| 1439 | cls: type[MODEL], |
| 1440 | objects: Iterable[MODEL], |
| 1441 | batch_size: int | None = None, |
| 1442 | ignore_conflicts: bool = False, |
| 1443 | update_fields: Iterable[str] | None = None, |
| 1444 | on_conflict: Iterable[str] | None = None, |
| 1445 | using_db: BaseDBAsyncClient | None = None, |
| 1446 | ) -> BulkCreateQuery[MODEL]: |
| 1447 | """ |
| 1448 | Bulk insert operation: |
| 1449 | |
| 1450 | .. note:: |
| 1451 | The bulk insert operation will do the minimum to ensure that the object |
| 1452 | created in the DB has all the defaults and generated fields set, |
| 1453 | but may be incomplete reference in Python. |
| 1454 | |
| 1455 | e.g. ``IntField`` primary keys will not be populated. |
| 1456 | |
| 1457 | This is recommended only for throw away inserts where you want to ensure optimal |
| 1458 | insert performance. |
| 1459 | |
| 1460 | .. code-block:: python3 |
| 1461 | |
| 1462 | User.bulk_create([ |
| 1463 | User(name="...", email="..."), |
| 1464 | User(name="...", email="...") |
| 1465 | ]) |
| 1466 | |
| 1467 | **db_default behaviour:** Fields with ``db_default`` that are not explicitly |
| 1468 | set will use the database DEFAULT. However, within a single ``bulk_create`` |
| 1469 | call, each ``db_default`` field must be treated consistently across *all* |
| 1470 | instances — either every instance provides an explicit value, or none of |
| 1471 | them do. Mixing explicit values and database defaults for the same field |
| 1472 | raises :exc:`~tortoise.exceptions.OperationalError`. |
| 1473 | |
| 1474 | :param on_conflict: On conflict index name |
| 1475 | :param update_fields: Update fields when conflicts |
| 1476 | :param ignore_conflicts: Ignore conflicts when inserting |
| 1477 | :param objects: List of objects to bulk create |
| 1478 | :param batch_size: How many objects are created in a single query |
| 1479 | :param using_db: Specific DB connection to use instead of default bound |
| 1480 | |
| 1481 | :raises OperationalError: If a ``db_default`` field has mixed usage across |
| 1482 | instances (some provide a value, others rely on the database default). |
| 1483 | """ |
| 1484 | return cls._db_queryset(using_db, for_write=True).bulk_create( |
| 1485 | objects, batch_size, ignore_conflicts, update_fields, on_conflict |
| 1486 | ) |
| 1487 | |
| 1488 | @classmethod |
| 1489 | def first(cls, using_db: BaseDBAsyncClient | None = None) -> QuerySetSingle[Self | None]: |