gpt4 book ai didi

django - 删除后模型对象是否可用?

转载 作者:行者123 更新时间:2023-12-04 18:10:16 28 4
gpt4 key购买 nike

如果我从数据库中获取所有对象,然后使用 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?

是否可以立即为每个客户刷新每次迭代中的值?因此,在处理 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

最佳答案

这是摘自 the docs :

Model.delete([using=DEFAULT_DB_ALIAS]) Issues a SQL DELETE for the object. This only deletes the object in the database; the Python instance will still exist and will still have data in its fields.

For more details, including how to delete objects in bulk, see Deleting objects.

If you want customized deletion behavior, you can override the delete() method. See Overriding predefined model methods for more details.

我不明白为什么要在第一个循环中嵌套第二个循环:对于每个对象,删除所有对象然后保存对象?

cust = Customer.objects.all():

#delete all
for c in Customer.objects.all():
c.delete()

恕我直言,这更清楚了。我会尝试解释应该发生什么(不是 100% 确定,从未尝试过类似的事情)。

  • cust 是一个 QueryDict 对象,正如文档所说,它仍然填充
  • 您的数据库现在清空了与客户模型相关的所有数据

您现在应该能够遍历 cust 并再次保存每个对象。

注意应该,这很重要

关于django - 删除后模型对象是否可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15416708/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com