What is the difference between the declarative_base() and db.Model?
The quickstart tutorial for the Flask-SQLAlchemy plugin instructs users to create table models inheriting the
db.Model class, e.g.
app = Flask(__main__) db = SQLAlchemy(app) class Users(db.Model): __tablename__ = 'users' ...
Base = declarative_base() class Users(Base): __tablename__ = 'users' ...
What is the difference between these two approaches?
Looking in the Flask-SQLAlchemy source code the
db.Model class is initialized as follows:
self.Model = self.make_declarative_base()
And here is the
def make_declarative_base(self): """Creates the declarative base.""" base = declarative_base(cls=Model, name='Model', metaclass=_BoundDeclarativeMeta) base.query = _QueryProperty(self) return base
_BoundDeclarativeMeta metaclass is a subclass of SQLAlchemy's
DeclarativeMeta, it simply adds support for computing a default value for
__tablename__ (the table name) and also to handle binds.
base.query property enables Flask-SQLAlchemy based models to access a query object as
Model.query instead of SQLAlchemy's
_QueryProperty query class is also subclassed from SQLAlchemy's query. The Flask-SQLAlchemy subclass adds three additional query methods that do not exist in SQLAlchemy:
I believe these are the only differences.
★ Back to homepage or read more recommendations: