我使用的是多表继承模型。
from django.db import models
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
class Restaurant(Place):
serves_hot_dogs = models.BooleanField(default=False)
serves_pizza = models.BooleanField(default=False)
class Cinema(Place):
sells_tickets = models.BooleanField(default=False)
sells_popcorn = models.BooleanField(default=False)
class Coffee(Place):
sells_tea = models.BooleanField(default=False)
我有一个创建几个不同模型的视图:
items = [
Restaurant(...),
Restaurant(...),
Restaurant(...),
Cinema(...),
Cinema(...),
Coffee(...),
Coffee(...),
# + 1.000 other items
]
for item in items:
item.save()
显然,这是非常低效的,因为它会创建大量的查询。不幸的是,Django还没有为多表继承提供批量创建方法(有一个打开的pull请求(。优化此代码的最佳方法是什么?我必须编写一个原始SQL查询吗?或者有其他方法吗?
我通过检查bulk_create
的实现来解决它。它使用InsertQuery
类生成SQLINSERT INTO
语句。IMHO这比编写原始SQL查询更干净、更短。
# 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()