8

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 Answers 3

15

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.

Sign up to request clarification or add additional context in comments.

2 Comments

well, my views.py has a line db=SQLAlchemy(app). Next line is import models. Then, in the models.py, the first line is
Amazing answer. Thanks, you saved my time :). Keep doing good work.
12

Instead of

from models import User

use

from models import *

2 Comments

Worked for me for some reason. I would love to know why this works?
I would like to know the same? Why does import * work?
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.