Issue
I have numerous models (OtherModels) associated with one main model (A). In the future, more models will be added. In my main model (A), which is connected to the others, I want to dynamically check whether any record from this main model (A) is related to other tables or not. What solution do you recommend?
class A(models.Model):
name = models.CharField(_('Name'), max_length=255)
class OtherModels(models.Models):
a = models.ForeignKey(A, on_deleted=models.PROTECT)
I use related_name
and it's working, But since my relationships have become numerous, I can't use this method, and in the future, as it seems to me, it's not the right approach, especially considering they are expected to increase further.
Solution
I write a code to get related relations of a model and it works well for me, I have a MainModel that all of my models inherit of it and I wrote a method on it to access this method on all of my models:
def has_relation(self, ignore_models=None) -> bool:
"""
check if there is a relation from other models to this instance or not
:param ignore_models: list of ignore models, should be model a.s. [Ticket, User]
:return: True => there is a relation to this record
"""
if ignore_models is None:
ignore_models = []
# ---
try:
for obj in self._meta.related_objects:
field_name = obj.identity[0].name
model = obj.identity[0].model
lookup = {
"is_deleted": False,
field_name: self.id
}
if model in ignore_models:
continue
# ---
relation_count = model.objects.filter(**lookup).count()
if relation_count > 0:
return True
# ---
return False
except:
return True
Answered By - javad mohammadi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.