8
votes

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?

3

3 Answers

15
votes

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.

11
votes

Instead of

from models import User

use

from models import *
0
votes

In this case, you are importing the models into views.py therefore if you need a class from models, import it from views.py and the circular import problem will be resolved.