问题
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
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
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))
and create_all.py
from db import db
db.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?
回答1:
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.
来源:https://stackoverflow.com/questions/42914302/flask-sqlalchemy-create-all-without-having-to-import-models