2

I'm trying to set up Flask-migrate for an app, but the first migration file always contains SQL to drop all tables rather than build them up.

Here is my app structure:

# app/__init__.py
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)

# app/models.py
from . import db

class Location(db.Model):
    __tablename__ = 'locations'

    id = db.Column(db.Integer, primary_key=True)
    city = db.Column(db.String(80), unique=True, nullable=False)
    city_url_slug = db.Column(db.String(80), unique=True, nullable=False)
    hotels = db.relationship('Hotel', backref='location', lazy='dynamic')

    def __repr__(self):
        return self.city

class Hotel(db.Model):
    __tablename__ = 'hotels'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), nullable=False)
    url = db.Column(db.String(80))
    free_parking = db.Column(db.Boolean())
    self_parking = db.Column(db.Boolean())

# manage.py
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app, db

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

if __name__ == '__main__':
    manager.run()

I create my database by going into the shell and running db.create_all(). I then run python manage.py db init, then python manage.py db migrate. But the result is a migration file that includes:

def upgrade():
    op.drop_table('locations')
    op.drop_table('hotels')

How can I fix my code so it detects either that no changes are required, or that it needs to build up all of the tables and fields?

Casey
  • 2,611
  • 6
  • 34
  • 60
  • 1
    I'd guess that `from app import app, db` isn't getting the `db` object that you think it is. If you import `db` from `models.py` in `manage.py`, you're more likely to get the db object you want. As it is, you're essentially importing `SQLAlchemy(app)`, an empty db. – Merbs May 08 '16 at 10:58
  • Merbs - that solved it, thank you! – Casey May 09 '16 at 01:51

0 Answers0