作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
是否有确保模型实例没有任何相关对象的选项?即,如果 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/
我是一名优秀的程序员,十分优秀!