python - 表子集列的连接将返回对象而不是 sqlalchemy 上的数据
问题描述
尝试做一些 SQLAlchemy 巫术:
- 数据库有 2 个反映的表
- 创建子集列结构的基本声明
- 进行连接查询
- 检索结果
代码如下:
db_tables = ["descriptor","desc_attribute"]
db_engine = create_engine(<REMOVED>, echo = True)
db_metadata = MetaData()
db_metadata.reflect(bind=db_engine, only=db_tables)
Session = sessionmaker(db_engine)
session = Session()
DescriptorTable = db_metadata.tables[db_tables[0]]
AttributeTable = db_metadata.tables[db_tables[1]]
Base = declarative_base()
class DescriptorTable2(Base):
__table__ = DescriptorTable
__mapper_args__ = {
'include_properties' :[
DescriptorTable.c.descriptor_id,#PK
DescriptorTable.c.desc_attribute_id, #FK
DescriptorTable.c.desc_attribute_standard_id],
}
class AttributeTable2(Base):
__table__ = AttributeTable
__mapper_args__ = {
'include_properties' :[
AttributeTable.c.desc_attribute_id, #PK
AttributeTable.c.dataset_id,
AttributeTable.c.source_attribute_description,
AttributeTable.c.source_attribute_unit,
]
}
上面的部分生成了 2 个以列作为子集的新派生表
然后对特定记录进行连接:
result = session.query(DescriptorTable2,AttributeTable2).
join(AttributeTable2).filter(DescriptorTable2.descriptor_id == 20662).all()
它生成了以下 SQL:
SELECT descriptor.descriptor_id AS descriptor_descriptor_id, descriptor.desc_attribute_id AS descriptor_desc_attribute_id, descriptor.desc_attribute_standard_id AS descriptor_desc_attribute_standard_id, desc_attribute.desc_attribute_id AS desc_attribute_desc_attribute_id, desc_attribute.dataset_id AS desc_attribute_dataset_id, desc_attribute.source_attribute_description AS desc_attribute_source_attribute_description, desc_attribute.source_attribute_unit AS desc_attribute_source_attribute_unit
FROM descriptor JOIN desc_attribute ON desc_attribute.desc_attribute_id = descriptor.desc_attribute_id
WHERE descriptor.descriptor_id = %(descriptor_id_1)s
SQL 看起来正确,但返回结果对象类似于:
(<__main__.DescriptorTable2 object at 0x7ff0fb7d8780>, <__main__.AttributeTable2 object at 0x7ff0fb7d8828>)
做对象自省我看不到任何结果或内容
但是,如果我在连接中声明列:
result = session.query(DescriptorTable2.desc_attribute_standard_id,
AttributeTable2.dataset_id,
AttributeTable2.source_attribute_description,
AttributeTable2.source_attribute_unit,
).join(AttributeTable2).filter(DescriptorTable2.descriptor_id == 20662).all()
结果具有正确的结构:
('Spectral near infra red reflectance (NIR)', 'WD-ISIS-NIR', 'Spectral near infra red (NIR) for 205 wavelengths', 'nm')
在 JOIN 上声明列与我拥有一个新声明的表并使用非常简单的 JOIN 语句的目标背道而驰。
那么,这种方法有什么问题,它可以使它起作用(想太多了吗?)
解决方案
对物体更好的内省揭示了
result[0][0].desc_attribute_standard_id
'Spectral near infra red reflectance (NIR)'
第一项是DescriptorTable2
并包含该表中的属性
推荐阅读
- html - 部分未出现在标题下方
- cmake - 在 Linux 上安装构建谷歌云存储 cpp 库的问题
- css - 有人可以帮助我使用 bootstrap4 轮播指示器吗
- git - 与 Git 集成的 DevOps 存储库的链接是什么?
- sql - 在 Oracle SQL 错误中将日期传递给存储过程:ORA-01858
- javascript - 返回对象列表中具有最大点属性的对象名称
- node.js - NodeJS为什么没有打开安全选项的SMTP服务器工作?
- mongodb - $geoNear maxDistance 限制为~200km
- eclipse - Eclipse 在构建后步骤中找不到 shell 脚本
- hyperledger-fabric - Hyperledger Fabric:“模拟”和“执行”的确切含义