簡體   English   中英

從 SqlAlchemy 表中獲取所有列以對其進行過濾

[英]Get all columns from a SqlAlchemy table to filter on them

我為表的所有列構建默認的相等過濾器,然后僅在幾列上添加/覆蓋我想要的特定過濾器,如下所示:

# Table definition

class OrderTable(Base):
    __tablename__ = "orders"

    id = Column(Integer, unique=True, nullable=False, primary_key=True)
    name = Column(String, nullable=False)

# Build all default filters for this table

table_filters = {column.name: lambda value: column == value for column in OrderTable.__table__.columns}

# Add/override specific filters

all_filters = {**table_filters, "name": lambda value: OrderTable.name.like(value)}

# Execute the query

query = ...
query = query.filter(all_filters["id"](123)) 
query.delete()

但是我在使用默認過濾器時收到此警告:

SAWarning: Evaluating non-mapped column expression 'orders.id' onto ORM instances; this is a deprecated use case.  Please make use of the actual mapped columns in ORM-evaluated UPDATE / DELETE expressions.

有沒有更好的方法讓所有列能夠在不收到此警告的情況下對其進行過濾?

我嘗試了不同的方法來使用OrderTable.__mapper__.attrsinspect(OrderTable).attrs獲取表的所有列,但是過濾器不起作用。

我不習慣發帖,所以請告訴我是否可以改進我的問題,我會對其進行編輯。

它似乎與從表中獲取列與直接使用屬性有關。

當您直接使用 attibute 時,您會得到一個InstrumentedAttribute ,當您從__table__.columns中獲取列時,您會得到一個Column

使用該Column ,您會收到該警告:

id_filter_col = OrderTable.__table__.c["id"] == 1

query = session.query(OrderTable)
query = query.filter(id_filter_col)
query.delete()  # SAWarning: Evaluating non-mapped column expression 'orders.id' onto ORM instances...

但是現在當您使用InstrumentedAttribute時:

id_filter_attr = OrderTable.id == 2

query = session.query(OrderTable)
query = query.filter(id_filter_attr)
query.delete()  # OK

您可以通過__mapper__.all_orm_descriptors從映射器訪問屬性,這應該可以解決您的問題。

class OrderTable(Base):
    __tablename__ = "orders"

    id = Column(Integer, unique=True, nullable=False, primary_key=True)
    name = Column(String, nullable=False)

table_filters = {column.key: lambda value: column == value for column in OrderTable.__mapper__.all_orm_descriptors}

all_filters = {**table_filters, "name": lambda value: OrderTable.name.like(value)}

query = ...
query = query.filter(all_filters["id"](123)) 
query.delete()  # OK

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM