声明性_base()和 db.Model 之间的区别是什么?

Flask-SQLAlchemy 插件的 快速启动教程指示用户创建继承 db.Model类的表模型,例如。

app = Flask(__main__)
db = SQLAlchemy(app)
class Users(db.Model):
__tablename__ = 'users'
...

然而,SQLAlchemy 教程和 bottSQLAlchemy自述都表明表模型继承了从 declarative_base()实例化的 Base

Base = declarative_base()
class Users(Base):
__tablename__ = 'users'
...

这两种方法的区别是什么?

17430 次浏览

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 make_declarative_base() method:

def make_declarative_base(self):
"""Creates the declarative base."""
base = declarative_base(cls=Model, name='Model',
metaclass=_BoundDeclarativeMeta)
base.query = _QueryProperty(self)
return base

The _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.

The base.query property enables Flask-SQLAlchemy based models to access a query object as Model.query instead of SQLAlchemy's session.query(Model).

The _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: get_or_404(), first_or_404() and paginate().

I believe these are the only differences.