编写sqlalchemy表列的子脚本
我正在尝试编写一个类,它将在sqlalchemy反射的表中查找特定的列类型,然后根据数据类型对列的子集执行一些操作。
我可以正确地反映该表,并获取一个'date‘类型列的列表,如date_types列表中所示。但是,当它到达table[name]
时,函数会失败,并显示以下错误:
*** TypeError: 'DeclarativeMeta' object is not subscriptable
如果我使用点下标而不是方括号,即table.col_name
,我可以访问表列属性,但我不知道如何使用该语法遍历属性列表。
下面是我的类:
from pdb import set_trace
class dateRangeProfiler():
def __init__(self, session):
self.date_ranges = {}
self.date_types = [Date(), DateTime(), TIMESTAMP()]
self.session = session
print('date data types: ', str(self.date_types))
def __call__(self, table):
date_columns = self.getDateColumns(table)
print(date_columns)
date_column_profile = self.profileColumns(table, date_columns)
return date_column_profile
def getDateColumns(self, table):
columns = [(c.name, c.type) for c in table.__table__.columns if str(c.type) in [str(dt) for dt in self.date_types]]
return columns
def profileColumns(self, table, date_cols):
profile = {}
for (name, _) in date_cols:
set_trace()
print(name)
qry = self.session.query(func.max(table[name]).label("max_date"),
func.min(testTable[name]).label("min_date"),) # <-- fails here
res = qry.one()
max = res.max_date
min = res.min_date
profile.append({name: {'max':max, 'min':min}})
下面是我调用分析器的方法:
date_range_profiler = dateRangeProfiler(sess)
date_range_profiler(my_table)
以及错误:
*** TypeError: 'DeclarativeMeta' object is not subscriptable
转载请注明出处:http://www.cospi.net/article/20230331/2355946.html