3

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 :)

Simon Otter
  • 173
  • 1
  • 3
  • 13

3 Answers3

2

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.

Sergey Shubin
  • 3,040
  • 4
  • 24
  • 36
  • Thanks Sergey. I hadn't realised that .all() was missing. Weird how I could use the unfinished query to loop through the objects in jinja (even though it was unfinished) but length filter didn't work. – Simon Otter Aug 18 '16 at 15:44
  • @SimonOtter It's possible: `Query` object works as generator, you can iterate through it without calling `all()`. This feature can also be used in jinja templates, so your loop code worked well. – Sergey Shubin Aug 20 '16 at 19:49
  • I imagine this is not applicable if `items` is very very large. – Alessandro De Simone Jul 05 '20 at 15:19
1

Use {{ items | count }} in jinja template

SumanKalyan
  • 1,681
  • 14
  • 24
0

Try to add loopcontrol extension

app.jinja_env.add_extension('jinja2.ext.loopcontrols')

Then

{% for item in items %}
{{loop.length}}
{% break %}
{% endfor %}