Sqlalchemy limit/offset returns incorrect result for pagination

Viewed 261

I have a correct query

    my_query = session.query(Task).join(
    Job, Job.id == Task.job_id
    ).join(
        User, User.id == Task.member
    )

After this I want to implement some sorting:

        sort_func = 'asc' if '-' not in data['sort'] else 'desc'
        sort_key = data['sort'].replace('-', '')
        sort_map = {
            'task_name': Task.name,
            'created_at': Task.created_at,
        }
        query = query.order_by(getattr(sort_map[sort_key], sort_func)())

Lets imagine that this query returns the following results:

   [{id: 1, task_name: 'Metallica'},{id: 2, task_name: 'soad'},{id: 3, task_name: 'elasticsearch'},{id: 4, task_name: 'bee'},{id: 5, task_name: 'one'},{id: 6, task_name: 'football'},{id: 7, task_name: 'mars'},{id: 8, task_name: 'hello'},{id: 9, task_name: 'apple'},{id: 10, task_name: 'car'},{id: 11, task_name: 'ford'}];

After this I want to implement pagination (with dynamic offset):

query = query.offset(offset).limit(5)

I expect that after first request my response is first five items from the list above:

   [{id: 1, task_name: 'Metallica'},{id: 2, task_name: 'soad'},{id: 3, task_name: 'elasticsearch'},{id: 4, task_name: 'bee'},{id: 5, task_name: 'one'}]

and after second request:

[{id: 6, task_name: 'football'},{id: 7, task_name: 'mars'},{id: 8, task_name: 'hello'},{id: 9, task_name: 'apple'},{id: 10, task_name: 'car'}]

But for the second page I get some items from the first page. For example:

    [{id: 2, task_name: 'soad'},{id: 7, task_name: 'mars'},{id: 8, task_name: 'hello'},{id: 9, task_name: 'apple'},{id: 1, task_name: 'Metallica'}]

Does anybody know why offset/limit distorts my result? Or maybe this isn't offset/limit problem

0 Answers
Related