thclpr
thclpr

Reputation: 5938

Return field name and value from SQLAlchemy result

How could i get the table column name and value using sqlalchemy?

Using what i have, i'm able to retrieve:

(2, 'blue', 'square')

But what i would like to get is :

{'id': 2, 'color': 'blue', 'type': 'square'}

Bellow, what i wrote after reading this documentation for version 0.9:

ConnectionManager.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sqlalchemy
from sqlalchemy import Table, MetaData
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base


location = 'localhost'
engine_str = 'mysql+mysqlconnector://xx:xx@{}/xx'.format(location)
engine = sqlalchemy.create_engine(engine_str, echo=False)
session = sessionmaker(bind=engine)
connection = engine.connect()
session = session(bind=connection)
metadata = MetaData()
Base = declarative_base()

class SelectType(object):
    """
    Server's details on database
    """
    def go(self, s, cc, pp):
        __table__ = Table('servers', metadata, autoload=True, autoload_with=engine)
        result = s.query(__table__).filter_by(color=cc).filter_by(type=pp).all()
        return result

def select_type(e, p):
    """
    return SelectType result
    """
    try:
        return SelectType().go(session, e, p)
    except:
        raise
    finally:
        session.close()

mainfile.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from resources import connection_manager

if __name__ == "__main__":
    try:
for i in connection_manager.select_type('blue', 'square'):
    print(i)

its important to note that i'm using autoload

Upvotes: 3

Views: 3297

Answers (2)

van
van

Reputation: 76962

With using Query.column_descriptions here you go:

class SelectType(object):
    def go(self, s, cc, pp):
        __table__ = Table('servers', metadata, autoload=True, autoload_with=engine)
        result = s.query(__table__).filter_by(color=environment).filter_by(type=pp)
        column_names = [c["name"] for c in result.column_descriptions]
        return [dict(zip(column_names, row)) for row in result.all()]

Upvotes: 5

John Ruddell
John Ruddell

Reputation: 25842

I am fairly new to this so I may be misunderstanding your question. but it looks like you want your data in JSON.

I dont know if you have access to the key with the connection_manager.select_type, but one thing thats worth trying is this:

for k,v in connection_manager.select_type('blue', 'square'): print(k) print(v)

where k is the key and v is the value. that could be a possible way of iterating through it.

This question is semi related to another post here: SQLAlchemy: Knowing the field names and values of a model object? which may help you as well. Good luck!

Upvotes: 2

Related Questions