首页 > 解决方案 > 表子集列的连接将返回对象而不是 sqlalchemy 上的数据

问题描述

尝试做一些 SQLAlchemy 巫术:

代码如下:

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 语句的目标背道而驰。

那么,这种方法有什么问题,它可以使它起作用(想太多了吗?)

标签: pythonsqlalchemy

解决方案


对物体更好的内省揭示了

result[0][0].desc_attribute_standard_id
'Spectral near infra red reflectance (NIR)'

第一项是DescriptorTable2并包含该表中的属性


推荐阅读