Python 2.7.9 Django 1.7 MySQL 5.6
我想填充一大堆属于多个类的对象实例,将它们堆叠成一个类似 create()
的查询,打开数据库连接,执行查询,然后关闭.我的主要动机是性能,但代码紧凑也是一个优势。
bulk_create()
的功能似乎正是我想要的,但我至少违反了列出的警告之一 here , 即
It does not work with many-to-many relationships.
和
It does not work with child models in a multi-table inheritance scenario.
the source code 中也描述了这些限制因此:
# So this case is fun. When you bulk insert you don't get the primary
# keys back (if it's an autoincrement), so you can't insert into the
# child tables which references this. There are two workarounds, 1)
# this could be implemented if you didn't have an autoincrement pk,
# and 2) you could do it by doing O(n) normal inserts into the parent
# tables to get the primary keys back, and then doing a single bulk
# insert into the childmost table. Some databases might allow doing
# this by using RETURNING clause for the insert query. We're punting
# on these for now because they are relatively rare cases.
但是我尝试返回的错误是通用的
ValueError: Can't bulk create an inherited model
我的模型显然不包含任何多对多字段或外键。我不完全清楚他们指的是什么多表继承场景,所以我不确定这是否是我的问题。我希望我可以通过看起来像这样的结构溜走,但后来我得到了一般错误,所以没有骰子:
child class with OneToOneField---\
\
child class with OneToOneField----->---concrete parent class
/
child class with OneToOneField---/
就源代码中建议的解决方法而言,#1 不适合我,#2 看起来也没有吸引力,因为我认为这会牺牲我想要的性能提升。
是否有其他解决方法可以模拟 bulk_create()
,同时像这样处理继承并且不放弃性能提升?我需要回到原始 SQL 吗?我不介意为每个子对象类型创建一个单独的集合并执行一个单独的 INSERT
/create()
。
最佳答案
我确定的解决方法是将我收集的所有 create()
包装在 with transaction.atomic():
中.通过在所有 Python 返回之前不打开任何数据库连接或执行任何查询,这大大减少了运行时间。
缺点可能是,如果遇到任何错误,所有更改都将回滚并且数据库保持不变。这可以通过将 create()
分成批处理并围绕每个批处理打开和关闭事务来补救。 (在我的例子中,这不是我想要的行为,因为我想要所有数据或一个都不想要。)
关于mysql - Django - 高效批量创建继承模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27711677/