9

I am trying to create the tables for my models, which are defined in a separate module from my app. I call db.create_all(), but no tables are created and there are no errors. I've defined the models and imported them before calling create_all. Why doesn't this work?

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:123@localhost/flask'
db = SQLAlchemy(app)

from models import User

db.create_all()
db.session.commit()

models.py:

from flask.ext.sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class User(db.Model):
  __tablename__ = 'users'
  uid = db.Column(db.Integer, primary_key = True)
Community
  • 1
  • 1
user1592380
  • 34,265
  • 92
  • 284
  • 515

1 Answers1

21

You created two separate db instances, one along with the app and one along with the models. Each instance has it's own metadata that stores the tables defined on it. The one you're using to issue the create table statement was not the one that the models were defined on. You should use only one instance of the extension, importing it when needed.

myapp/__init__.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
db = SQLAlchemy(app)

# import the models *after* the db object is defined
from myapp import models

myapp/models.py:

from myapp import db

class User(db.Model):
    ...

create_tables.py:

from myapp import app, db

with app.app_context():
    db.create_all()

Other things to note:

  • You should structure your app as a package, so that everything is importable under one location.
  • flask.ext is deprecated, import the extension directly from its package name.
  • Flask-SQLAlchemy automatically generates __tablename__ from the class name, you don't need to define it yourself.
  • You do not have to call commit after create_all.
davidism
  • 121,510
  • 29
  • 395
  • 339