簡體   English   中英

使用對象屬性的SQLAlchemy動態查詢

[英]SQLAlchemy dynamic query using object attribute

我正在尋找動態查詢對象的屬性。 在執行時,我將不知道要使用哪個屬性或列。

class Product(Base):
    __tablename__ = 'products'

    sku = Column(String, primary_key=True)
    list_price = Column(String)
    status = Column(String)
    url = Column(String)
    special_price1 = Column(String)
    special_price2 = Column(String)
    special_price3 = Column(String)

我有一個SQLAlchemy基類Product ,它描述了一些屬性,以及與標價不同的其他特殊價格。

然后,我在下面有一個PriceList類,可以訪問其他資源和方法,這些資源和方法有助於報告和更新'products'表中的列。 此類存儲有關所有Product對象的唯一特價表的信息。

class PriceList:

    def __init__(self, name, db_col_name):
        # Display name
        self.name = name

        # Used for querying the database for a specific column
        # This will always be one of the 4 price related column names
        # list_price, special_price1, special_price2, or special_price3
        self.db_col_name = db_col_name

稍后,我開始遍歷每個ProductPriceList實例。

for product in products:
    for price_list in price_lists:
        # Do stuff

此時,我的product對象具有一個新的特殊價格,或多個新的特殊價格,我計划在數據庫中進行更新。 可以簡單地將我的對象添加到數據庫會話中並提交,但是在提交之前,我需要獲取舊價格並將其鏈接到各自的價目表。 舊價格用於報告中,然后通過電子郵件發送給我。 我現在在做什么如下

for product in products:
    sku = product.sku
    for price_list in price_lists:
        # New price
        new_price = product.__getattribute__(price_list.db_col_name)

        # Get the existing special price from the database
        old_price = s.query(Product.__getattribute__(Product, price_list.db_col_name)).filter(Product.sku.like(sku)).first()

我覺得我通過使用__getattribute __()使這個復雜化了。 它可以工作,但這似乎不是pythonic。 有誰知道在更新之前獲取未知列的值的更好方法? 數據庫更新大約每500個產品進行一次或兩次,因此在處理過程中將每個特殊價格存儲在外部變量中並不是十分有效。

要動態訪問屬性,應使用內置的getattr

new_price = getattr(product, price_list.db_col_name)

如果實例是陳舊的,則應使用Session.expire ,這意味着下次訪問屬性時,將從數據庫中檢索它們。

s.expire(product)

# or only expire price
s.expire(product, [price_list.db_col_name])

暫無
暫無

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

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