0

Hi I would like to import a model within a model. But It seems that I can't do it if both model are importing one another. To make it clear below is a sample code

# Files located in models with filename model_b.py
from repository.base_model import BaseModel
from models.model_a import ModelA

class ModelB(BaseModel):
     # properties and classes here
     # There's a join function here that make use of ModelA

Now I have another file which is named model_a that have a class of ModelA. I need to import ModelB as I need to do a join query.

# Files located in models with filename model_a.py
from repository.base_model import BaseModel
from models.model_b import ModelB

class ModelA(BaseModel):
     # properties and classes here
    def join_function(code, session):

      result = (session.query(ModelA).
                select_from(ModelA).
                join(ModelB, ModelB.id == ModelA.model_b_id).
                filter(ModelB.code == code).
                all())

If I run my script it say

ImportError: cannot import name 'ModelB'

Now if I remove the import of ModelB it works just fine. It seems that there is an issue when two Model are importing one another. Is there a solution to this?

MadzQuestioning
  • 3,341
  • 8
  • 45
  • 76

0 Answers0