在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

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

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

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

有沒有辦法能夠在批量操作之后返回的結果中攜帶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)老老實實的一條條的插入吧

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

2018年5月22日 18:46