How do I find the length of a list of objects in a jinja template when the list of objects has been created by querying a database?
I thought There are {{ items|length }} items in this category.
would work, but items is a result of:
items = db_session.query(Item).filter_by(category_id=category.id)
and I get the error
TypeError: object of type 'Query' has no len()
Obviously, I could calculate the length separately and pass into render_template()
, but I wondered if there was a better way?
Any help from the community would be much appreciated :)
items
object is not a list yet, it is an unprocessed Query
object as you see in the error. You can use Query.all()
method to get a list of items:
items = db_session.query(Item).filter_by(category_id=category.id).all()
After that length
filter can be applicable.