【发布时间】:2016-09-27 14:40:33
【问题描述】:
在寻找一种方法来检查是否可以在 django 中删除模型实例后,我发现了很多选项,但没有一个按预期工作。希望这个解决方案能有所帮助。
让我们从创建一个可以被其他模型继承的抽象模型类开始
class ModelIsDeletable(models.Model):
name = models.CharField(max_length=200, blank=True, null=True, unique=True)
description = models.CharField(max_length=200, blank=True, null=True)
date_modified = models.DateTimeField(auto_now_add=True)
def is_deletable(self):
# get all the related object
for rel in self._meta.get_fields():
try:
# check if there is a relationship with at least one related object
related = rel.related_model.objects.filter(**{rel.field.name: self})
if related.exists():
# if there is return a Tuple of flag = False the related_model object
return False, related
except AttributeError: # an attribute error for field occurs when checking for AutoField
pass # just pass as we dont need to check for AutoField
return True, None
class Meta:
abstract = True
示例
假设我们有三个模型 Organization and Department 和 StaffType 一个组织中可以有这么多部门 并且一个组织有一个特定的 StaffType
class StaffType(ModelIsDeletable):
pensionable = models.BooleanField(default=False)
class Organization(ModelIsDeletable):
staff_type = models.ForeignKey(to=StaffType)
class Department(ModelIsDeletable):
organization = models.ForeignKey(to=Organization, to_field="id")
所以在添加一些信息后说你想删除一个组织模型实例 已经绑定到一个部门
例如我们有 组织表 =>(名称 = 工程,pk = 1) 部门表 => (name=Developer, organization_fk=1, pk=1)
现在,当您尝试使用 pk 获取组织后删除组织时
a_org = Organization.objects.get(pk=1)
有了这个,你可以检查它是否可以删除
deletable, related_obj = a_org.is_deletable()
if not deletable:
# do some stuff with the related_obj list
else:
# call the delete function
a_org.delete()
【问题讨论】:
-
...里面有问题吗?
-
没有问题,只回答特定问题
-
这是我的 github 帐户中的 sn-p。
标签: python django django-models