I try to get the related model for a foreignkey field :
for field in Model._meta.fields:
if "ForeignKey" in str(type(field)):
exec("related_model = Model." + field.name + ".get_query_set().model")
This works fine in shell, line per line.
But not when in a def:
def run(self):
for field in Model._meta.fields:
if "ForeignKey" in str(type(field)):
exec("related_model = Model." + field.name + ".get_query_set().model")
It seems that the variable 'related_model' is not created or taken in account further in the code.
Thank you in advance for any suggestions?
exec
is a bad way to deal with this. Instead, use:
related_model = getattr(Model, field.name).get_query_set().model