문제

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top