程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何让 SQLAlchemy 从视图而不是表创建类?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决如何让 SQLAlchemy 从视图而不是表创建类??

开发过程中遇到如何让 SQLAlchemy 从视图而不是表创建类?的问题如何解决?下面主要结合日常开发的经验,给出你关于如何让 SQLAlchemy 从视图而不是表创建类?的解决方法建议,希望对你解决如何让 SQLAlchemy 从视图而不是表创建类?有所启发或帮助;

我正在使用flask-sqlalchemy,我想从视图而不是数据库表创建一个类。有没有表名的替代方案? 'Car' 最近从一个表变成了一个视图,现在它在发送请求时卡住了。

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)

解决方法

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,),(<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)  

大佬总结

以上是大佬教程为你收集整理的如何让 SQLAlchemy 从视图而不是表创建类?全部内容,希望文章能够帮你解决如何让 SQLAlchemy 从视图而不是表创建类?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。