Search code examples
pythonponyorm

Show last two ordered entities with Pony ORM


I'm learning to use Pony ORM, and with this MWE...

from pony import orm
db = orm.Database()
class Test(db.Entity):
    label = orm.Required(str)
db.bind(provider='sqlite',filename=':memory:')
db.generate_mapping(create_tables=True)
with orm.db_session:
    Test(label='text02')
    Test(label='text01')
    Test(label='text03')
orm.select(t for t in Test).order_by(lambda: t.label).filter(lambda: t.label > 'text01').show()

...I'm able to order entities the way I want and then use that to display the last two, knowing which will be the last two.

id|label
--+------
1 |text02
3 |text03

Is there a better way to show the last couple of tuples/rows in a relation/table, especially if I don't know which entities I'll want to filter out? I'd prefer to order the entities and then just show the last two, without having to provide the filter explicitly. Kind of like a BASH tail -n 2 can be used.


Solution

  • You can sort descending and take first two elements.

    orm.select(t for t in Test).order_by(lambda: desc(t.label)).limit(2)