| 2008 | |
| 2009 | |
| 2010 | class BulkCreateQuery(AwaitableQuery, Generic[MODEL]): |
| 2011 | __slots__ = ( |
| 2012 | "_objects", |
| 2013 | "_ignore_conflicts", |
| 2014 | "_batch_size", |
| 2015 | "_db", |
| 2016 | "_executor", |
| 2017 | "_update_fields", |
| 2018 | "_on_conflict", |
| 2019 | ) |
| 2020 | |
| 2021 | def __init__( |
| 2022 | self, |
| 2023 | model: type[MODEL], |
| 2024 | db: BaseDBAsyncClient, |
| 2025 | objects: Iterable[MODEL], |
| 2026 | batch_size: int | None = None, |
| 2027 | ignore_conflicts: bool = False, |
| 2028 | update_fields: Iterable[str] | None = None, |
| 2029 | on_conflict: Iterable[str] | None = None, |
| 2030 | ): |
| 2031 | super().__init__(model) |
| 2032 | self._objects = objects |
| 2033 | self._ignore_conflicts = ignore_conflicts |
| 2034 | self._batch_size = batch_size |
| 2035 | self._db = db |
| 2036 | self._update_fields = update_fields |
| 2037 | self._on_conflict = on_conflict |
| 2038 | |
| 2039 | def _analyze_db_default_fields(self, columns: list[str]) -> set[str]: |
| 2040 | """Classify each db_default field across all instances. |
| 2041 | |
| 2042 | Returns a set of field names to omit from the INSERT (all instances |
| 2043 | use DatabaseDefault for that field). Raises OperationalError if a |
| 2044 | field has mixed usage (some instances provide a value, others don't). |
| 2045 | """ |
| 2046 | |
| 2047 | fields_map = self.model._meta.fields_map |
| 2048 | db_default_field_names = [fn for fn in columns if fields_map[fn].has_db_default()] |
| 2049 | if not db_default_field_names: |
| 2050 | return set() |
| 2051 | |
| 2052 | omit_fields: set[str] = set() |
| 2053 | for field_name in db_default_field_names: |
| 2054 | has_default = False |
| 2055 | has_value = False |
| 2056 | for instance in self._objects: |
| 2057 | if isinstance(getattr(instance, field_name), DatabaseDefault): |
| 2058 | has_default = True |
| 2059 | else: |
| 2060 | has_value = True |
| 2061 | if has_default and has_value: |
| 2062 | raise OperationalError( |
| 2063 | f"Cannot use bulk_create() when field '{field_name}' has " |
| 2064 | f"db_default and some instances provide explicit values while " |
| 2065 | f"others rely on the database default. Either: " |
| 2066 | f"(a) set the value explicitly on ALL instances, " |
| 2067 | f"(b) omit it from ALL instances to use the database default, or " |
no outgoing calls
no test coverage detected
searching dependent graphs…