简体   繁体   中英

Django ImportError: cannot import from models

I have a utils.py file in an app directory at the same level as models.py . I am trying to import a class (a model) in utils.py :

from models import TeamConstraint

My IDE does not report any conflict, however when running the server I am getting an ImportError :

ImportError: cannot import name TeamConstraint

I tried checking for circular dependencies, there is a file tasks.py also in the same level as the rest that imports from utils.py :

from scheduler.utils import current_indie_teams, matchcount_by_week

Although I don't understand why here scheduler needs to be included explicitly, while when trying to import a model it is not required (or so says PyCharm at least).

I am trying to figure out how to solve this.

When you say from models import TeamConstraint it's not clear what models is.
It could be a different app with the name models or it could be the file in the same folder. It's better to be explicit than implicit.

Try using an absolute import from scheduler.models import TeamConstraint or if you really want to use a relative import do so as such from .models import TeamConstraint (Notice the . before models)

Also it seems like you are using Python3 but your PyCharm is configured for Python2, else it would warn you.

whenever you get import errors, try delaying one of the imports. here place 'from models import TeamConstraint' in class or function instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM