【问题标题】:How to get SQLAlchemy to create a class from a view instead of a table?如何让 SQLAlchemy 从视图而不是表创建类?
【发布时间】:2021-09-20 01:08:05
【问题描述】:

我正在使用flask-sqlalchemy,我想从视图而不是数据库表创建一个类。 tablename 有替代品吗? “汽车”最近从表格更改为视图,现在发送请求时卡住了。

class car(db.Model):
    __tablename__ = 'car'
    model = Column(Text, primary_key=True)
    brand = Column(Text, primary_key=True)
    condition = Column(Text, primary_key=True)
    year = Column(Integer)

【问题讨论】:

标签: sqlite sqlalchemy flask-sqlalchemy


【解决方案1】:

SQLAlchemy 对基于视图的 ORM 对象没有特别的问题。例如,这适用于 SQL Server,因为 SQL Server 允许对视图进行 DML(插入、更新、删除):

# set up test environment
with engine.begin() as conn:
    conn.exec_driver_sql("DROP TABLE IF EXISTS car_table")
    conn.exec_driver_sql("CREATE TABLE car_table (id integer primary key, make varchar(50))")
    conn.exec_driver_sql("INSERT INTO car_table (id, make) VALUES (1, 'Audi'), (2, 'Buick')")
    conn.exec_driver_sql("DROP VIEW IF EXISTS car_view")
    conn.exec_driver_sql("CREATE VIEW car_view AS SELECT * FROM car_table WHERE id <> 2")

Base = sa.orm.declarative_base()


class Car(Base):
    __tablename__ = "car_view"
    id = Column(Integer, primary_key=True, autoincrement=False)
    make = Column(String(50), nullable=False)

    def __repr__(self):
        return f"<Car(id={self.id}, make='{self.make}')>"


with Session(engine) as session:
    print(session.execute(select(Car)).all())
    # [(<Car(id=1, make='Audi')>,)]
    # (note: the view excludes the row (object) where id == 2)

    session.add(Car(id=3, make="Chevrolet"))
    session.commit()
    print(session.execute(select(Car)).all())
    # [(<Car(id=1, make='Audi')>,), (<Car(id=3, make='Chevrolet')>,)]

但是,如果您真的在使用 SQLite,那么您将无法使用基于视图的类来添加、更新或删除对象,因为 SQLite 不允许这样做:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) cannot modify car_view because it is a view  
[SQL: INSERT INTO car_view (id, make) VALUES (?, ?)]  
[parameters: (3, 'Chevrolet')]  
(Background on this error at: https://sqlalche.me/e/14/e3q8)  

【讨论】:

    猜你喜欢
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    相关资源
    最近更新 更多