Python 表子集列的联接在sqlalchemy上重新运行一个包含数据的对象
试着做一些炼金术巫毒:Python 表子集列的联接在sqlalchemy上重新运行一个包含数据的对象,python,sqlalchemy,Python,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 = sessio
- 数据库中有两个表被反射
- 创建列结构子集的基声明
- 进行联接查询
- 检索结果
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,
]
}
它生成了以下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>)
结果具有适当的结构:
('Spectral near infra red reflectance (NIR)', 'WD-ISIS-NIR', 'Spectral near infra red (NIR) for 205 wavelengths', 'nm')
在联接上声明列是为了实现我的目标,即创建一个新的声明表,并使用一个非常简单的联接语句
那么,这种方法有什么问题,它能使它起作用吗(过度思考?更好地反省对象揭示了
result[0][0].desc_attribute_standard_id
'Spectral near infra red reflectance (NIR)'
第一项是
DescriptorTable2
并包含该表中的属性没问题,结果是一个2元组的模型实例。您是对的,模型随后包含结果,只是希望结果是一个易于操作的对象。结果允许通过位置或名称访问实体。例如结果[0]。描述符表2
。
('Spectral near infra red reflectance (NIR)', 'WD-ISIS-NIR', 'Spectral near infra red (NIR) for 205 wavelengths', 'nm')
result[0][0].desc_attribute_standard_id
'Spectral near infra red reflectance (NIR)'