我正在寻找动态查询对象的属性。在执行时,我将不知道要使用哪个属性或列。
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)
我有一个Product
描述一些属性的SQLAlchemy基类,外加与标价不同的其他特殊价格。
然后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
后来我开始迭代在每个Product
和PriceList
实例。
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])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句