python批量创建对象的方法_django使用bulk_create批量创建,返回的对象不带pk(主键)...

自己回答一下吧, 翻看了django1.7 bulk_create 的源码, 上面有一段有意思的注释:

# 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.

解决方法有两种, 1)主键不设置为自增长,意思是需要自己指定主键的值喽?没理解错吧

2)老老实实的一条条的插入吧

想了一下还是一条条插入,放到事务里面去操作. 不知道还有没有更好的办法

你可能感兴趣的:(python批量创建对象的方法)