Объединение столбцов подмножества таблиц возвращает объект целых данных в sqlalchemy - PullRequest
0 голосов
/ 14 января 2020

Попытка сделать несколько 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 новые производные таблицы, столбцы которых имеют подмножество

Затем выполняется объединение для указанной c записи:

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.

Итак, что не так с этим подходом и может ли он заставить его работать rthinking?)

1 Ответ

0 голосов
/ 14 января 2020

Улучшение самоанализа объекта выявило

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

Первый элемент - DescriptorTable2 и содержит атрибуты из этой таблицы

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...