Skip to content
Advertisement

SQLAlchemy Model.query.get use generic function to get latest id

Consider this snippet. I am trying to get the user with the latest id like this:

User.query.get(func.max(User.id))

It throws an error saying Boolean value of this clause is not defined

How do I get the user with the largest id by using the model.query API?

Advertisement

Answer

I would solve it like:

last_user = User.query.order_by(User.id.desc()).first()

An alternative would be:

last_user = User.query.filter(
    User.id == select(func.max(User.id)).scalar_subquery()
)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement