PaolaJ.
PaolaJ.

Reputation: 11532

How to add pagination to query to return 10 results per page

I need to add pagination to my web form ( at the moment I have returned all from database but now there is too much).

    result = []
    session = Session()
    index = 1
    for user in session.query(UserModel).order_by(desc(UserModel.age)).all():
        result.append({'username' : user.username,
                       'nation' : user.nation,
                        'age' : user.age,
                         'rank' : index})
        index = index + 1

I need to put pagination (10 results per page, ordered by age). How to add pagination to query ?

Upvotes: 1

Views: 4871

Answers (1)

laurie
laurie

Reputation: 708

Use limit(n) and offset (m) to get the next n rows from offset m. Your code should look as follows:

result = []
session = Session()
index = 1
for user in session.query(UserModel).order_by(desc(UserModel.age)).offset(m).limit(n).all():
    result.append({'username' : user.username,
                   'nation' : user.nation,
                    'age' : user.age,
                     'rank' : index})
    index = index + 1

Upvotes: 5

Related Questions