i_trope
i_trope

Reputation: 1604

flask_sqlalchemy create_all without having to import models

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?

Upvotes: 3

Views: 995

Answers (1)

Ilja Everilä
Ilja Everilä

Reputation: 53017

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.

Upvotes: 1

Related Questions