Search code examples
pythonforeign-key-relationshipflask-sqlalchemy

Flask, SQLAlchemy, Foreign Keys


Hello I have some Problem with some foreign keys.

I have something like this:

class Foo(db.Model):
    """The foo object."""
    __tablename__ = 'foos_foo'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.Text, unique=True)
    content = db.Column(db.Text)
    bar = db.relationship('Bar', backref='bars_bar')
    bar_id = db.Column(db.Integer, db.ForeignKey('bars_bar.id'))


class Bar(db.Model):
    """The bar object."""
    __tablename__ = 'bars_bar'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text, unique=True)
    description = db.Column(db.Text)
    status = db.Column(db.SmallInteger, default=NEW)

I use this configuration style: https://github.com/mitsuhiko/flask/wiki/Large-app-how-to

So I have something like this:

from app.foos.views import mod as foosModule
from app.bars.views import mod as barsModule

app.register_blueprint(foosModule)
app.register_blueprint(barsModule)

If I call like in the config style from Mitsuhiko, python shell.py, comes this error:

sqlalchemy.exc.OperationalError: (OperationalError) no such table: bars_bar u'SELECT bars_bar.id AS bars_bar_id, bars_bar.name AS bars_bar_name, bars_bar.description AS bars_bar_description, bars_bar.status AS bars_bar_status \nFROM bars_bar' ()

What goes on there? Yes the table is not there because I will create it? Is there a way to create some tables before some other? Or what do I wrong?

Thanks for your time!


Solution

  • Quoting Flask-SQLalchemy docs:

    To create the initial database, just import the db object from a interactive Python shell and run the SQLAlchemy.create_all() method to create the tables and database:

    from yourapplication import db
    db.create_all()