简体   繁体   中英

How to iterate a column to get the sub list in sqlalchemy?

I would like to acquire the sub list from a table like this using sqlalchemy:

Column1    Column2
   a          1
   a          2
   b          1
   b          2

and firstly get

Column1    Column2
   a          1
   a          2

and secondly get

Column1    Column2
   b          1
   b          2

Can I realize it by executing the query language once?

You can do it with a single query, but you need to perform the grouping in Python. To do that you could use itertools.groupby to process the query results which you would order by ( column1 , column2 ). Here is an example:

from itertools import groupby
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()
class Stuff(Base):
    __tablename__ = 'stuff'
    id = Column(Integer, primary_key=True)
    column1 = Column(String(10))
    column2 = Column(String(10))

    def __repr__(self):
        return '({}, {})'.format(self.column1, self.column2)

db_url = 'sqlite:////tmp/test.db'
engine = create_engine(db_url)
Base.metadata.bind = engine
session = sessionmaker(bind=engine)()

for k, g in groupby(session.query(Stuff).order_by(Stuff.column1, Stuff.column2),
                    key=lambda stuff: stuff.column1):
    print('{}: {}'.format(k, ','.join(stuff.column2 for stuff in g)))

If your table contains this data:

Column1    Column2
   a          1
   a          2
   b          1
   b          2
   a          3

the output would be:

a: 1,2,3
b: 1,2

To process the data replace the print() in the for loop with your processing code.

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