简体   繁体   中英

How can i remove the parentheses of a query result from sqlalchemy

I know this is something really simple to do but i'm not recalling how should i do it.

Basically, I want the result returned from the function select_data to be like:

['something','something_a','something_b']

and not like, what is currently being returned:

[(u'something',), (u'something_a',)(u'something_b',)]

Following, the block of the code that i'm using:

import sqlalchemy
from sqlalchemy import Table, exc, and_
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from configurations import config_loader

hostname = config_loader.get('db_config', 'hostname')
db_name = config_loader.get('db_config', 'db_name')
db_port = config_loader.get('db_config', 'db_port')
login = config_loader.get('db_config', 'db_login')
pwd = config_loader.get('db_config', 'db_pwd')
sample_table = config_loader.get('db_tables', 'some_table')


con_string = 'mysql+mysqlconnector://{login}:{passwd}@{hostname}:{port}/{db}'

engine_str = con_string.format(
    login=login, passwd=pwd, hostname=hostname, port=db_port, db=db_name
)

try:
    engine = sqlalchemy.create_engine(engine_str, echo=False)
    session = sessionmaker(bind=engine)
    connection = engine.connect()
    session = session(bind=connection)
    Base = declarative_base()
except exc.SQLAlchemyError:
    raise


def select_data(server):
    t = Table(some_table, Base.metadata, autoload_with=engine)
    stm = session.query(t.c.data_name).filter(
        t.c.server == server
    )
    return stm.all()

Your code returns list of tuples . You should extract tuples adding the following code:

raw_data = select_data(server)
data = [item[0] for item in raw_data]

One more way to the extracting:

import operator

raw_data = select_data(server)
data = map(operator.itemgetter(0), raw_data)

More information about SQLAlchemy .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM