【发布时间】:2020-07-31 14:47:31
【问题描述】:
我正在编写一个脚本,在开发过程中应该删除数据库并用一些虚拟值填充它。不幸的是,它的 drop_all() 部分不起作用:
from flask_sqlalchemy import SQLAlchemy
from my_app import create_app
from my_app.models import Block
db = SQLAlchemy()
def main():
app = create_app()
db.init_app(app)
with app.app_context():
db.session.commit()
db.drop_all() # <- I would expect this to drop everything, but it does not
db.session.commit()
db.create_all() # <- This works even if the database is empty
b1 = Block(name="foo")
db.session.add(b1) # <- Every time I run the script, another copy is added
db.session.commit()
blocks = Block.query.all()
for b in blocks:
print(b) # <- this should contain exactly one record every time, but keeps getting longer
而my_app.models.py 包含:
from . import db
class Block(db.Model):
__tablename__ = "block"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30))
drop all 显然没有删除正确的表。我在 SO 和其他来源上找到的示例倾向于基于同一文件中的 db.Model(例如here)在同一文件中定义要素类,而我无法做到这一点。我需要以某种方式将导入的类绑定到数据库吗?如果有,怎么做?
【问题讨论】:
标签: python flask sqlalchemy