问题描述
背景、目的
- 应由实际行组成,
- 应该允许使用跨任何层次结构深度的联接(例如父/子/孙...等)跨相关表进行查询
目前的方法
我已经反映了数据库,并且正在使用 SLQAlchemy 的 inspect
查找所有相关表。迭代这个方法 n 次应该让我遍历 n 个深度级别的层次结构:
from sqlalchemy import create_engine,select,MetaData,Table,func,inspect
from sqlalchemy.orm import Session
from sqlalchemy.ext.automap import automap_base
import pyMysqL
Metadata = MetaData()
db_connection_str = f'MysqL+pyMysqL://{db_user}:{db_password}@localhost/{db_name}'
Base = automap_base()
Base.prepare(db_connection,reflect=False)
Event = Base.classes.event # Here,'Event' is the root/main table from where the traversal begins
num_rows = 10 # Sample
stmt = select(*inspect(Event).persist_selectable.columns).limit(num_rows)
with Session(db_connection) as session:
resultlist = session.execute(
stmt
).all()
'''
Store the Event table query result somehow
'''
'''
Following section is a first-level traversal. This needs to be iterated to get nth-level traversals
'''
sample_event_id_list = [row[0] for row in resultlist] # 1st column is ID,is there a better way that involves key mapping rather than integer indexing?
sample_event_id_list
for rel in inspect(Event).relationships:
object_class = rel.mapper.class_
stmt = select(*inspect(object_class).persist_selectable.columns).\
join(Event).\
where(Event.id.in_(sample_event_id_list))
'''
Store the Event table query result somehow
'''
问题
我看过 Factory Boy,它与 sqlAlchemy 集成,还可以从实际数据生成行样本。但是否可以遍历数据库中所有相关表尚不清楚。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)