python-3.xflaskflask-sqlalchemyflask-migratesqlalchemy-migrate

Flask-migrate No changes in schema detected


I am trying to understand how flask and sqlalchemy works.Below is my app structure

enter image description here

init.py contains

import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
import User

# Create a login manager object
login_manager = LoginManager()

app = Flask(__name__)

# Often people will also separate these into a separate config.py file
app.config['SECRET_KEY'] = 'mysecretkey'
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
Migrate(app, db)

model.py

from test import db
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin



class User(db.Model, UserMixin):
    # Create a table in the db
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(64), unique=True, index=True)


    def __init__(self, email, username, password,first_name,last_name):
        self.email = email

and app.py

# This is app.py, this is the main file called.
from test import app
from flask import render_template


@app.route('/')
def index():
    return 'Hello World'


if __name__ == '__main__':
    app.run(debug=True)

and I am using below commands to create tables

  1. set FLASK_APP=
  2. flask db init
  3. flask db migrate -m

But flask migrate is not detecting table and displays below message

enter image description here

I am unable to figure how to resolve this issue.Could someone please highlight what I am doing wrong.Thanks


Solution

  • You need to import model in __init__.py

    import os
    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    from flask_migrate import Migrate
    from flask_login import LoginManager
    import User
    
    # Create a login manager object
    login_manager = LoginManager()
    
    app = Flask(__name__)
    
    # Often people will also separate these into a separate config.py file
    app.config['SECRET_KEY'] = 'mysecretkey'
    basedir = os.path.abspath(os.path.dirname(__file__))
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    
    db = SQLAlchemy(app)
    Migrate(app, db)
    from app import model
    

    This is because model.py depends on __init__.py