Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, Flask, SQLAlchemy: cannot import from models

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?

like image 970
kurtgn Avatar asked Sep 30 '14 17:09

kurtgn


1 Answers

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.

like image 73
SingleNegationElimination Avatar answered Sep 21 '22 14:09

SingleNegationElimination