gpt4 book ai didi

sqlite - Flask-SQLAlchemy:如何更改表结构?

转载 作者:行者123 更新时间:2023-12-05 02:59:40 25 4
gpt4 key购买 nike

我在 flask 应用程序中有一个表格模型:

class Article(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(80), nullable=False)
body = db.Column(db.Text, nullable=False)
pubDate = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now())

然后我使用 db.crate_all()db.add()/db.session 向上表添加一些数据,工作顺利!

然后我想更新和添加类文章的一些属性:

class Article(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(80), nullable=False)
body = db.Column(db.Text, nullable=False)
createDate = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now())
touchDate = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now())
publishDate = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now())
isVisible = db.Column(db.Boolean, nullable=False, default=True)
isDraft = db.Column(db.Boolean, nullable=False, default=True)

更新类文章后,我再次使用 db.create_all()。当我运行我的 flask 应用程序时,我收到以下错误消息:

cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such column: article.createDate
[SQL: SELECT article.id AS article_id, article.title AS article_title, article.body AS article_body, article."createDate" AS "article_createDate", article."touchDate" AS "article_touchDate", article."publishDate" AS "article_publishDate", article."isVisible" AS "article_isVisible", article."isDraft" AS "article_isDraft"
FROM article
WHERE article."isVisible" = 1]

每当我更改 db.Model 子类时,数据库中的表会自动同步吗? db.Model子类的属性改变后需要做什么操作?

最佳答案

对于工业级解决方案,Flask-Migrate是一个扩展,使用 Alembic 处理 Flask 应用程序的 SQLAlchemy 数据库迁移.

Alembic is a database migration tool written by the author of SQLAlchemy. A migrations tool offers the following functionality:

  • Can emit ALTER statements to a database in order to change the structure of tables and other constructs
  • Provides a system whereby “migration scripts” may be constructed; each script indicates a particular series of steps that can “upgrade” a target database to a new version, and optionally a series of steps that can “downgrade” similarly, doing the same steps in reverse.
  • Allows the scripts to execute in some sequential manner.

也可以执行原始 SQL ALTER TABLE 语句。

参见 How to execute raw SQL in Flask-SQLAlchemy app

关于sqlite - Flask-SQLAlchemy:如何更改表结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57676602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com