I've got a weird problem.
I am building a Flask app with SQLAlchemy. I have a file with models, namely, models.py. And I have a User model there.
If I open my "views.py" and insert a string
import models
and then use the User model like
u=models.User.query.filter_by(name='John',password='Doe').first()
everything works fine.
But if instead of "import models" i put
from models import User
Python crashes and says:
ImportError: cannot import name User
how can this be possible?
you most likely have a circular import; your, lets say 'app' module:
# app.py
import models
...
def doSomething():
models.User....
but your models
module also imports app
import app
class User:
...
since models
imports app
, and app
imports models
, python has not finished importing models
at the point app
tries to import models.User
; the User
class has not been defined (yet). Either break the cyclic import (make sure models
doesn't import anything that also imports models
), or you'll just have to make do with models.User
instead of the shorter User
in app
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With