Django model relationship infos with on_delete property
I want to know what models are children of a model with on_delete property. As I know like below if we have ownerModel which is parent of childModel1 and check1Model:
import uuid
from django.db import models
class ownerModel(models.Model):
ownerId = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False, blank=True)
class check1Model(models.Model):
checkId = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False, blank=True)
owner=models.ForeignKey(ownerModel,on_delete=models.CASCADE)
class childModel1(models.Model):
childId = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False, blank=True)
check2=models.ForeignKey(ownerModel,on_delete=models.CASCADE)
then we can get what models are children of ownerModel with a code like this:
class myView(views.APIView):
def get(self, request, format=None):
for f in ownerModel._meta.get_fields():
if 'field' in f.__dict__.keys():
print('***childModels***')
print(f.__dict__)
print()
return Response({'0000'}, status=status.HTTP_200_OK)
I mean by checking if the field key is in __dict__.keys() in items of ownerModel._meta.get_fields()
ofc so like here we get extended info about children models:
***childModels***
{'field': <django.db.models.fields.related.ForeignKey: owner>, 'model': <class 'Users.models.ownerModel'>, 'related_name': None, 'related_query_name': None, 'limit_choices_to': {}, 'parent_link': False, 'on_delete': <function
CASCADE at 0x00000286550848B0>, 'symmetrical': False, 'multiple': True, 'field_name': 'ownerId', 'related_model': <class 'Users.models.check1Model'>, 'hidden': False}
***childModels***
{'field': <django.db.models.fields.related.ForeignKey: check2>, 'model': <class 'Users.models.ownerModel'>, 'related_name': None, 'related_query_name': None, 'limit_choices_to': {}, 'parent_link': False, 'on_delete': <function CASCADE at 0x00000286550848B0>, 'symmetrical': False, 'multiple': True, 'field_name': 'ownerId', 'related_model': <class 'Users.models.childModel1'>, 'hidden': False}
so I find these 2 conditions necessary to get child models info:
- in child models making sure child relationship is set up with a line like line below:
models.ForeignKey(ownerModel,on_delete=models.CASCADE)
- as said "if the
fieldkey is in__dict__.keys()in items ofownerModel._meta.get_fields()" to get children info.
but the problem is that in some cases I can't get the children info from parent model. so:
-
it makes me wonder if are these 2 conditions are enough to find out which models are children of a model or not?
-
are there other similar ways to get which models are children of a model?
btw I want to have on_delete also and having on_delete is the only reason I am using _meta.get_fields() over _meta.fields because _meta.fields doesn't provide on_delete property.
Comments
Post a Comment