Skip to content Skip to sidebar Skip to footer

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, 'colo

Solution 1:

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()]

Solution 2:

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!

Post a Comment for "Return Field Name And Value From Sqlalchemy Result"