SqlAlchemy 通过外键更新 table

SqlAlchemy update table through foreign key

我的 sqlalchemy

中有 2 个 table

本书table

class Book(Base):
    __tablename__ = 'books'

    rowid = Column(Integer(), primary_key = True)
    name = Column(String(50), index = True)
    author = Column(String(50))
    year = Column(Integer())
    book_type = Column(Integer(), nullable = False)
    isloaned = Column(Boolean(), nullable = False, default = False)

贷款table

class Loans(db.Base):
    __tablename__ = 'loans'

    loan_id = Column(Integer(), primary_key = True)
    custID = Column(Integer(), ForeignKey(customers.Customer.rowid))
    bookID = Column(Integer(), ForeignKey(books.Book.rowid))
    loan_date = Column(DateTime())
    return_date = Column(DateTime())
    islate = Column(Boolean(), default = True, nullable = False)

    customername = relationship("Customer", foreign_keys = custID)
    bookname = relationship("Book", foreign_keys = bookID)

贷款 table 通过外键连接到图书 table。

现在我有一些代码,所以当我 return 一本书到图书馆时,它会更新借阅 return 日期。

用它我想更新书中的 isloaned 列, 我用这段代码尝试了一些东西:

def returnloan(loanid, date):
    with mydb.session as session:
        session.query(Loans).filter(Loans.loan_id == loanid).update({"return_date": date})
        session.query(Loans).filter(Loans.loan_id == loanid).update({"bookname.isloaned": False})
        session.commit()

但我得到一个错误

sqlalchemy.exc.InvalidRequestError: Invalid expression type: 'bookname.isloaned'

return 日期已更新,但我无法通过外键到达 book.isloaned

有什么建议吗?

您只需更新 Book。理想情况下,您还需要 Loans table 上的反向引用,以便您可以从 Book:

访问它
bookname = relationship("Book", foreign_keys=bookID, backref="loans")

使用 SQLAlchemy 1.4 语法,您将更新如下内容:

stmt = update(Loans).where(Loans.loan_id == loan_id).values(return_date=date)
session.execute(stmt)

stmt = update(Book).where(Book.loans.has(Loans.load_id == loan_id)).values(isloaned=False)
session.execute(stmt)

我认为使用您当前的语法,这可能有效:

session.query(Book).filter(Book.loans.has(Loans.load_id == loan_id)).update({"isloaned": False})

或者,这将是仅使用 ORM 的超级简单方法:

loan = session.execute(select(Loans).where(Loans.loan_id == loan_id)).scalar()
loan.return_date = date
loan.book.isloaned = False