how to get the position of the current record of the result of a query?

Issue #3255 closed
Gildson Bezerra created an issue

I have 1 record table of people and I need to make a query and then immediately send the list of people to a ranking. I would like to know how best to do this operation. (Without using func.row_number())

thanks

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

Base = declarative_base()

class People(Base):
    __tablename__ = 'peoples'
    _id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(50))
    points = Column(Integer)

engine = create_engine('sqlite:///db.sqlite')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)

def run():
    session = Session()

    session.add_all([People(name='Alice', points=190),
                     People(name='George', points=215),
                     People(name='Nick', points=167),
                     People(name='Alex', points=210),
                     People(name='Paul', points=233)])
    session.commit()


    peoples = session.query(People) \
        .filter(People.points > 200) \
        .order_by(People.points.desc()) \
        .all()

    for p in peoples:
        # How I Can Get Position of Current Register in Peoples Here?
        position = 0 #position = p.?
        print('%s - %s (%s)' % (position, p.name, p.points))

if __name__ == '__main__':
    run()

Comments (2)

  1. Mike Bayer repo owner

    this is a mailing list issue, since it's a usage question, not a report on a bug or a specific feature request.

    as for the question itself, maybe I'm missing something but it seems like you just want to use enumerate() on the list:

    for position, p in enumerate(peoples):
        # ...
    

    im not really sure what else it is you'd be trying to get there.

  2. Gildson Bezerra reporter

    I'm using SQLAlchemy with Flask to create a quiz at the end where he tells the user the position he was in the rankings.

    I need to know the position of a record in 2 times 1st time when the match ended'll see which User ranking position was.

    2nd time to some quiz screen will have to show the matches with highest score.

    In these two moments need of the particular record position. I could use a "for" to pick up these positions, but believed that there should be another way to associate a position to these records. Having now a wider view of the objective of the association of records to a position you indicate me use even enumerate or is there another way to do these operations without much performance loss.

    Thanks for the previous answer

  3. Log in to comment