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,
Flask-SQLAlchemy Query Returns the Database Class and the Data.
Querying Records For this purpose Flask-SQLAlchemy provides a query attribute on your Model class. When you access it you will get back a new query object over all records. You can then use methods like filter() to filter the records before you fire the select with all() or first() .
At the ORM level, the speed issues are because creating objects in Python is slow, and the SQLAlchemy ORM applies a large amount of bookkeeping to these objects as it fetches them, which is necessary in order for it to fulfill its usage contract, including unit of work, identity map, eager loading, collections, etc.
As the documentation says, all() returns the result of the query as a list.
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() }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With