简体   繁体   English

SqlAlchemy 通过外键更新表

[英]SqlAlchemy update table through foreign key

i have 2 tables in my sqlalchemy我的 sqlalchemy 中有 2 个表

book 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)

and loans 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)

with the loans table connecting to the book table via foreign key.贷款表通过外键连接到书表。

now i have a bit of code so when i return a book to the library it updates the loan return date.现在我有一些代码,所以当我把书还给图书馆时,它会更新借还日期。

with it i want to update the isloaned column inside book, i tried something with this code:我想用它更新书中的 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()

but i get an error但我得到一个错误

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

the return date is updated but i cant reach the book.isloaned through the foreign key归还日期已更新,但我无法通过外键找到这本书。

any suggestions?有什么建议么?

You just have to update Book .你只需要更新Book You'll also ideally need a backref on the Loans table so you can access it from Book :理想情况下,您还需要Loans表上的反向引用,以便您可以从Book访问它:

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

Using the SQLAlchemy 1.4 syntax, you would update something like this:使用 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)

I think with your current syntax, this might work:我认为使用您当前的语法,这可能有效:

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

Alternatively, this would be the super easy way just using the ORM:或者,这将是仅使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM