Python : Solving this cyclic import conundrum

2019-07-27 09:44发布

问题:

I am running into an import conundrum. After adding a new import I am getting the following error

from studentApp.models import modelStudent
  File abc, line 6, in <module>
    from interviewApp.models import modelInterviewQuestion
  File "xyz", line 4, in <module>
    from mainApp.models import modelPatient
ImportError: cannot import name modelPatient

Now this is what my file looks like mainApp/models.py

from studentApp.models import modelStudent #<---Added this and I get the error

and this is in my studentApp/models.py file

from interviewApp.models import modelInterviewQuestion #---> has a call to modelPatient inside
from mainApp.models import modelPatient 
from labApp.models import modelLabTestName #---> has a call to modelPatient inside

Now in my interviewApp/models.py I have this which is causing a cyclic import

from mainApp.models import modelPatient #<---This is what is initiated the call

I understand why this is happening but I am not sure how to fix this problem. Any suggestions ?

回答1:

The circular dependency is that studentApp/models.py imports mainApp.models and mainApp/models.py imports studentApp.models. One solution is to move modelPatient into it's own module and then import it into mainApp/models.py and studentApp/models.py.