Question

I was wondering if anyone knows how to output the number of results from a query in a flask template.

Example view code:

products = Product.query.all()

In the template it would be handy to be able to just do:

{{ products.count() }}

Is there anyway to do this already, or does anyone have a filter written that does this?

Cheers,

Was it helpful?

Solution

Your products template variable is a regular list. You can use the length filter to gets its size:

{{ products|length }}

But if you are working with paginated results then this will give you the size of one page. If you want the size of the entire query then you have to call count() on the query object. For example:

product_count = Product.query.count()

Then pass this to the template as an additional argument. Or if you prefer you can pass the query object to the template and call count() from there:

{{ product_query.count() }}

OTHER TIPS

you can use len(products) , it is standart python function and works for me

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top