在寻找一种方法来检查模型实例是否可以在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
示例
因此,假设我们有三个模型:组织、部门和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)
现在,当您使用主键获取组织后,尝试删除组织时
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()
https://stackoverflow.com/questions/39727624
复制相似问题