表子集列的连接在 sqlalchemy 上重新调整数据中的对象



Try do some SQLAlchemy voodoo:

  • 数据库有 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,包含该表中的属性

最新更新