1. 程式人生 > 其它 >ArgumentError("subject table for an INSERT, UPDATE or DELETE expected, got Column('id', Integer(), table=<user>, primary_key=True, nullable=False)."

ArgumentError("subject table for an INSERT, UPDATE or DELETE expected, got Column('id', Integer(), table=<user>, primary_key=True, nullable=False)."

python專案中,如果使用的 SQLAlchemy 操作資料庫,當表名和對應的專案中的物件名不一樣時,更新資料時會報錯

ArgumentError("subject table for an INSERT, UPDATE or DELETE expected, got Column('id', Integer(), table=<user>, primary_key=True, nullable=False)."

資料庫表名

user

資料庫表對應的物件

class UserInfo(BaseModel):
    __tablename__ = "user"
    # ID
id = Column(Integer, primary_key=True, nullable=False) ...

物件是通過 __tablename__ 屬性做了和資料庫表的對映

---

更新資料的程式碼(報錯時),注意粗體標紅部分

    with session_commit_maker() as db_session:
        result = db_session.query(UserInfo.id)\
            .filter(UserInfo.id == uid)\
            .update({"name": new_name})

將以上粗體標紅部分改為 UserInfo 即可解決該問

    with session_commit_maker() as db_session:
        result = db_session.query(UserInfo)\
            .filter(UserInfo.id == uid)\
            .update({"name": new_name})