django使用bulk_create批量创建,返回的对象不带pk(主键)

使用django的bulk_create进行批量插入操作(未指定主键), 返回对象列表, 其中的对象主键为None。

有没有办法能够在批量操作之后返回的结果中携带pk。

阅读 6.6k
1 个回答

自己回答一下吧, 翻看了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)老老实实的一条条的插入吧

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题