[英]SqlAlchemy update table through foreign key
我的 sqlalchemy 中有 2 个表
书桌
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)
和贷款表
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)
贷款表通过外键连接到书表。
现在我有一些代码,所以当我把书还给图书馆时,它会更新借还日期。
我想用它更新书中的 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'
归还日期已更新,但我无法通过外键找到这本书。
有什么建议么?
你只需要更新Book
。 理想情况下,您还需要Loans
表上的反向引用,以便您可以从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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.