鍍金池/ 問答/Python/ django使用bulk_create批量創(chuàng)建,返回的對(duì)象不帶pk(主鍵)

django使用bulk_create批量創(chuàng)建,返回的對(duì)象不帶pk(主鍵)

使用django的bulk_create進(jìn)行批量插入操作(未指定主鍵), 返回對(duì)象列表, 其中的對(duì)象主鍵為None。

有沒有辦法能夠在批量操作之后返回的結(jié)果中攜帶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)主鍵不設(shè)置為自增長,意思是需要自己指定主鍵的值嘍?沒理解錯(cuò)吧
2)老老實(shí)實(shí)的一條條的插入吧

想了一下還是一條條插入,放到事務(wù)里面去操作. 不知道還有沒有更好的辦法

2018年5月22日 18:46