如果我從數據庫中獲取所有對象,然後使用python foreach循環遍歷它們,然後在循環中刪除它們中的所有對象。刪除的數據庫條目仍作爲客戶對象存在於內存中會發生什麼情況是刪除後可用的模型對象嗎?
for cust in Customer.objects.all():
#delete all
for cust2 in Customer.objects.all():
cust2.delete()
#what is cust now??
cust.save() # is this valid?
是否可以立即刷新每個cust的每次迭代中的值?因此,雖然處理cust1,我刪除cust2,那麼在接下來的迭代,我不開始處理cust2 ...想象一下:
for cust in Customer.objects.all():
if cust.pay_everyone():
for cust2 in Customer.objects.all():
cust2.paid = True
cust2.save()
#when cust2 comes in the loop, cust2.paid is still False
#the previous pay_everyone() method is undone
if cust.kill_everyone():
for cust2 in Customer.objects.all():
cust2.delete()
#when cust2 comes in the loop, he is still alive when he should be dead
cust.save()
# in cust2's turn in the loop, he has been just resurrected which is not possible
我添加了第二個示例 – siamii 2013-03-14 18:49:44
不介意,cust2和cust是客戶的兩個不同副本,它們都包含相同的數據,最後保存cust會將其值返回到db中。你的cust2循環只是從數據庫中刪除數據,但最外面的Customer循環存儲了一個包含數據庫初始值的臨時查詢集。它不介意如果你的內部循環全部刪除它們,Customer.objects.all()仍然包含原始值 – 2013-03-15 10:48:12
我想避免此同步錯誤的唯一解決方案是在循環開始時手動刷新每個Cust。像'cust = cust.refresh()' – siamii 2013-03-15 13:22:49