After finding a way to check if it is possible to delete the model instance in django, I came across many examples, but did not work properly. Hope this solution can help.
Let's start by creating an abstract model class that can be inherited by another model.
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):
Example
So, let's say we have three models Organization and Department and StaffType So many Departments can be in the Organization And the Organization has a certain 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")
so let's say by adding some information that you want to delete an instance of an organization model that is already tied to the Department
For example, we have Organization Table => (name = Engineering, pk = 1) Department table => (name = Developer, organization_fk = 1, pk = 1)
Now when you try to delete the organization after receiving it with pk
a_org = Organization.objects.get(pk=1)
With this you can check if it is deleted
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()
pitaside
source share