flask_sqlalchemy create_all without having to import models

為{幸葍}努か 提交于 2020-02-04 03:47:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!