【问题标题】:Do you still need to create SQLAlchemy models if the DB already exists?如果数据库已经存在,你还需要创建 SQLAlchemy 模型吗?
【发布时间】:2021-12-04 03:31:22
【问题描述】:

Flask 和 SQL 的新手 - 自学构建一个相当基本的网络应用程序。

到目前为止,我所学的课程并没有让我清楚现有的 SQLite 数据库如何与 SQLAlchemy 交互。

我已经在我的终端中使用 SQL 创建了一个 SQLite 数据库,该数据库已经设置了我想要使用的表。

现在希望使用 SQLAlchemy 将其连接到我的 Flask 应用程序。例如,假设这是我数据库中 Book 表的模型,具有以下 SQL 设置:

CREATE TABLE "Book" (
    "isbn"  INTEGER NOT NULL,
    "title" TEXT NOT NULL,
    "author"    TEXT NOT NULL,
    PRIMARY KEY("id" AUTOINCREMENT)
)

像下面这样在 Flask 应用程序中概述模型的目的是为了让应用程序知道如何与数据库交互吗?

class Book(db.Model):
    isbn = db.column(db.Integer, primary_key = True)
    title = db.column(db.String(50), unique = False, index = True)
    author = db.column(db.String(50), unique = True, index = True)

鉴于所提供的几乎所有信息都翻倍了 - 有没有更有效的方法可以从已经建立的数据库中导入这样的模型?

【问题讨论】:

    标签: python sqlite flask sqlalchemy


    【解决方案1】:

    您添加新行表名,旧主题here Document

    class Book(db.Model):
         __tablename__ = 'Book'
        isbn = db.column(db.Integer, primary_key = True)
        title = db.column(db.String(50), unique = False, index = True)
        author = db.column(db.String(50), unique = True, index = True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 2011-10-16
      • 2018-01-28
      • 2015-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多