Flask-SQLAlchemy create_all如何发现要创建的模型? [英] How does Flask-SQLAlchemy create_all discover the models to create?
问题描述
Flask-SQLAlchemy的db.create_all()
方法创建与我定义的模型相对应的每个表.我从不实例化或注册模型的实例.它们只是从db.Model
继承的类定义.它怎么知道我定义了哪些模型?
Flask-SQLAlchemy's db.create_all()
method creates each table corresponding to my defined models. I never instantiate or register instances of the models. They're just class definitions that inherit from db.Model
. How does it know which models I have defined?
推荐答案
Flask-SQLAlchemy没什么特别的,它都是SQLAlchemy的标准部分.
Flask-SQLAlchemy does nothing special, it's all a standard part of SQLAlchemy.
调用 db.create_all
最终会调用与已定义的MetaData
实例相关的.确切的机制在SQLAlchemy中非常circuit回,因为在幕后进行了大量簿记工作,所以我大大简化了解释.
Calling db.create_all
eventually calls db.Model.metadata.create_all
. Tables are associated with a MetaData
instance as they are defined. The exact mechanism is very circuitous within SQLAlchemy, as there is a lot of behind the scenes bookkeeping going on, so I've greatly simplified the explanation.
db.Model
是声明性基类,它具有一些特殊的元类行为.定义后,它将在内部创建一个MetaData
实例,以存储其为模型生成的表.子类db.Model
的子类,其元类行为将记录db.Model._decl_class_registry
中的类以及db.Model.metadata
中的表.
db.Model
is a declarative base class, which has some special metaclass behavior. When it is defined, it creates a MetaData
instance internally to store the tables it generates for the models. When you subclass db.Model
, its metaclass behavior records the class in db.Model._decl_class_registry
as well as the table in db.Model.metadata
.
仅在导入包含类的模块时定义它们.如果您在某处编写了模块my_models
,但从未导入过该模块,则其代码将永远不会执行,因此这些模型也不会被注册.
Classes are only defined when the modules containing them are imported. If you have a module my_models
written somewhere, but it is never imported, its code never executes so the models are never registered.
这可能是关于SQLAlchemy如何检测模型的一些困惑的来源.不会为子类扫描"模块,没有使用db.Model.__subclasses__
,但是将模块导入到 所需的位置才能执行代码.
This may be where some confusion about how SQLAlchemy detects the models comes from. No modules are "scanned" for subclasses, db.Model.__subclasses__
is not used, but importing the modules somewhere is required for the code to execute.
- 包含模型的模块已导入并执行.
- 执行模型类定义,子类
db.Model
- 模型的表已注册到
db.Model.metadata
- Module containing models is imported and executed.
- Model class definition is executed, subclasses
db.Model
- Model's table is registered with
db.Model.metadata
这篇关于Flask-SQLAlchemy create_all如何发现要创建的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!