3

Is there any best practice for pagination with Pony ORM?

I'm seeing others have these has_next and has_previous helper methods but in Pony I'm on my own.

So far this is what I have, a couple of Jinja helpers:

# Jinja helpers for pagination
def next_page(current, max_page):
    if current >= max_page:
        return False
    else:
        return current + 1


def prev_page(current, max_page):
    if current < 2:
        return False
    else:
        return current - 1 

max_page is calculated like this: math.ceil(MyTable.select().count()/PAGE_SIZE)

But gets a little tedious, you have to keep sending current page and max page all around.

{% if maxpage > 1 %}
    {% if prev_page(page, maxpage) %}
    <a href="{{ url_for('index', pagenum=prev_page(page, maxpage)) }}"><</a>
    {% endif %}

    {% if next_page(page, maxpage) %}
    <a href="{{ url_for('index', pagenum=next_page(page, maxpage)) }}">></a>
    {% endif %}
{% endif %}

So am I missing something? Any better way?

MGP
  • 2,981
  • 35
  • 34

2 Answers2

2

You can query a pagination

q = models.select(d for d in models.Thingy)
page = 1
count = q.count()
results_of_first_page = q.page(page, 20)
pages = int(count/20)
if pages > 20:
    pages = 20
nadermx
  • 2,596
  • 7
  • 31
  • 66
  • I see in the official docs, they want to sort the query before doing the `.page()`: `Product.select().order_by(lambda p: desc(p.price)).page(1)` Do you know if the `.sort()` can be skipped, like in your example? I wonder if the order would be random and then the pages would have duplicated objects? – Michael Boesl Jul 22 '22 at 08:19
2

Fast solution, may be not the best

@app.route('/persons-list/<int:page>') 
def persons_list(page):
    LIMIT = 10
    items = select(p for p in models.Person)
    return render_template('persons_list.html',
                            maxpage=items.count()//LIMIT,
                            page=page,
                            items=items.page(page, LIMIT))

in template:

{% if maxpage > 1 %}
    {% if page - 1 >= 1 %}
        <a href="{{ url_for('persons_list', page=page-1) }}"><</a>
    {% endif %}

    Page {{ page }} of {{ maxpage }}

    {% if page + 1 <= maxpage %}
        <a href="{{ url_for('persons_list', page=page+1) }}">></a>
    {% endif %}
{% endif %}
Andrey Topoleov
  • 1,591
  • 15
  • 20