gpt4 book ai didi

python - django 一次重写删除级联

转载 作者:行者123 更新时间:2023-11-28 18:06:24 30 4
gpt4 key购买 nike

是否有确保模型实例没有任何相关对象的选项?即,如果 Person 对象有任何相关对象,我想要这一行

person.delete()

引发错误。

而且我不想为每个外键修改 on_delete=models.CASCADE。我只在这里需要这种保护,对于我的应用程序中的任何其他情况(比如 django 管理站点)我更喜欢级联行为。

最佳答案

这符合你的要求吗?

has_related = False
for field in person.__class__._meta.get_fields():
if field.is_relation:
field_name = field.get_accessor_name()
model_field = getattr(person, field_name)
if not isinstance(model_field, models.Model) and model_field.all():
has_related = True
break

if not has_related:
person.delete()

关于python - django 一次重写删除级联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53204945/

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