Reputation: 7034
Is there an option for to make sure that a model instance does not have any related objects? i.e, if the Person object has any related objects, I want this line
person.delete()
to raise an error.
And I don't want to modify on_delete=models.CASCADE
for every foreign key. I need this protection only here, for any other case in my application (like django admin site) I do prefer the cascading behavior.
Upvotes: 4
Views: 361
Reputation: 3376
Does this correspond to what you want?
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()
Upvotes: 1