This is application.py file:
db = SQLAlchemy()
migrate = Migrate()
db.app = app
db.init_app(app)
migrate.init_app(app, db)
I find out that, I can declare model with two different ways.
from application import db
class MyModel(db.Model):
id = db.Column(db.Integer, primary_key=True)
or
from sqlalchemy import Model, Column, Integer
class MyModel(Model):
id = Column(Integer, primary_key=True)
Which one is right or what all these means?
They are both correct. One uses flask-sqlalchemy the other just uses 'raw' sqlalchemy.
The advantages of 'pure' sqlalchemy is that the models can more easily be used outside of the flask application.
If you are not planning on using them outside flask, just stick with the method described in the flask-sqlalchemy docs as it will save you a lot of time and effort.
Flask sqlalchemy is just a lightweight extension to make it easier to integrate sqlalchemy with flask.
Simply put, it handles the database connection code integrated with flask requests, and adds some convenient functionalities, for. Instance, access Model
, Column
, session
, engine
, and other useful sqlalchemy classes directly from the db
object