2๐
โ
I solved it by inspecting the implementation of bulk_create
. Underlying it uses the InsertQuery
class to generate the SQL INSERT INTO
statement. IMHO this is much cleaner and shorter than writing a raw SQL query.
# Create all concrete models at once
items = Place.objects.bulk_create(items)
# Group items by their model
item_mapping = defaultdict(list)
for item in items:
item_mapping[type(item)].append(item)
# Create a bulk insert for each model
for model, items in item_mapping.items():
fields = model._meta.local_concrete_fields
query = sql.InsertQuery(model)
query.insert_values(fields, items)
query.get_compiler(connection=connection).execute_sql()
๐คNepo Znat
Source:stackexchange.com