flask_sqlalchemy create_all无需导入模型 [英] flask_sqlalchemy create_all without having to import models
问题描述
我试图了解如何设置一个调用create_all
的独立脚本,而不必将我的所有模型导入其中.以下是相关文件:
I am trying to understand how to set up a standalone script that calls create_all
without having to import all my models into it. Below are the relevant files:
db.py
db.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
test_model.py
test_model.py
from db import db
class TestTable(db.model):
id = db.Column(db.Integer, primary_key=True)
foo = db.Column(db.String(80))
和 create_all.py
and create_all.py
from db import db
db.create_all()
但是,create_all
不会执行任何操作,因为它不会检测到已注册的任何表,除非将它们导入.声明模型时是否有办法将它们添加到注册表"中以绕过显式导入?
However, create_all
will not do anything, as it does not detect any tables registered to it, unless they are imported. Is there a way when declaring models to have them added to the "registry" to bypass the explicit import?
推荐答案
总之,没有.您将必须在调用create_all()
之前以一种或另一种方式导入这些模型.声明类创建Table
实例,并在构造类本身时将其添加到MetaData
.如果MetaData
不包含表,则create_all
将不执行任何操作.
In a word, no. You will have to import those models before the call to create_all()
, one way or the other. The declarative classes build the Table
instances and add them to the MetaData
when the class itself is constructed. If the MetaData
contains no tables, create_all
will do nothing.
以另一种方式,除非对那些声明进行评估,否则声明模型"将不执行任何操作,因此必须执行该模块.从它导入就可以做到这一点.
Put another way, "declaring models" does nothing unless those declarations are evaluated, so the module must be executed. Importing from it does just that.
这篇关于flask_sqlalchemy create_all无需导入模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!