cannot import name 'db' from partially initialized module 'models' (most likely due to a circular import)


I am able to run my flask tests utilizing the following command python -m unittest discover -p but when I try to run python runserver it shows me the following error message:

Traceback (most recent call last):
  File "", line 10, in <module>
    from models import db
  File "/home/paula/projects/envioclicktest/restaurant_flask/", line 1, in <module>
    from app import app as app
  File "/home/paula/projects/envioclicktest/restaurant_flask/", line 10, in <module>
    from models import db
ImportError: cannot import name 'db' from partially initialized module 'models'
(most likely due to a circular import) (/home/paula/projects/envioclicktest/restaurant_flask/

My project structure is the following:


Here’s the content of my files as well as the line I think is causing trouble in each of them

from flask import Flask
from flask_script import Manager, Shell
from flask_migrate import Migrate, MigrateCommand

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///restaurant.db'

from models import db
migrate = Migrate(app, db)

manager = Manager(app)
manager.add_command('db', MigrateCommand)

if __name__ == '__main__':

from app import app as app <-------Trouble line Originally "from __main__ import app" but that doesnt work with
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql.functions import func
from sqlalchemy.exc import IntegrityError
import datetime
import pytz
import random
mx = pytz.timezone('America/Mexico_City')

db = SQLAlchemy(app)

class Waiter(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128))
    services = db.relationship("Service", back_populates="waiter")

class Table(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    table_no = db.Column(db.String(128))
    services = db.relationship("Service", back_populates="table")
class Service(db.Model):

    def __init__(self, tip):
        time =
        self.tip = tip
        # check for waiters
        waiters = db.session.query(Waiter, func.count(\
        available_waiters= [i for i in waiters if i[1] < 4]
        available_waiters_length = len(available_waiters)
        # Check for tables
        tables = db.session.query(Table, func.count(\
        available_tables= [i for i in tables if i[1] < 1]
        available_tables_length = len(available_tables)
        #check if available 
        if available_tables_length == 0 and available_waiters_length == 0:
            raise Exception("not enough waiters or tables")
        if available_waiters_length == 0:
            raise Exception("not enough waiters")
        if available_tables_length == 0:
            raise Exception("not enough tables")
        # add waiter and table
        waiter_obj = random.choice(available_waiters)
        self.waiter_id = waiter_obj[0].id
        table_obj = random.choice(available_tables)
        self.table_id = table_obj[0].id

        # check if current time is open
        if time.time() < datetime.time(9,0) or time.time()> datetime.time(23, 30):
            raise Exception("The restaurant is closed")
        # add timedelta to init_time
        if time.time() < datetime.time(17,0):
            self.exit = time + datetime.timedelta(minutes=90)
        if time.time() > datetime.time(17,0):
            self.exit = time + datetime.timedelta(minutes=120)

    id = db.Column(db.Integer, primary_key=True)
    table_id = db.Column(db.Integer, db.ForeignKey(''))
    table = db.relationship("Table", back_populates="services")
    waiter_id = db.Column(db.Integer, db.ForeignKey(''))
    waiter = db.relationship("Waiter", back_populates="services")
    arrival = db.Column(db.DateTime,
    exit = db.Column(db.DateTime)
    tip = db.Column(db.Numeric(10,2))

from app import app as app <------- This line does not work as "from __main__ import app"
import unittest
from models import db, Waiter, Table, Service
from freezegun import freeze_time
import datetime
import pytz

class UserTest(unittest.TestCase):

    def setUp(self):
        app.config['SQLALCHEMY_DATABASE_URI']  = 'sqlite:///test.db'
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False = app.test_client()

    def tearDown(self):

    dt = datetime.datetime(2018,1,1,11,0,0,tzinfo=pytz.timezone('America/Mexico_City'))
    def test_models(self):
        #Create a Table and a Waiter
        table = Table(table_no="table1")
        waiter = Waiter(name="Juan")
        service = Service(tip=90.80)
        query =  Service.query.all()
        #Check that all users exist
        assert len(query) == 1
        assert query[0].table_id == 1
        assert query[0].waiter_id == 1
        assert ((query[0].exit-query[0].arrival).seconds/60) >= 90

I can’t figure it out and it’s driving me nuts.

Any help is much appreciated 🙂


I was able to find a workaround. In my I substituted this line:

from app import app as app

for this:

    from app import app as app
except ImportError:
    from __main__ import app

It works but it’s ugly. I thought there must be a prettier way to do this.

Answered By – paula.em.lafon

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published