Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-SQLAlchemy number of results in query

Tags:

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,

like image 560
Ben Kilah Avatar asked Nov 18 '13 06:11

Ben Kilah


People also ask

What does Flask-SQLAlchemy query return?

Flask-SQLAlchemy Query Returns the Database Class and the Data.

How do I query data in a SQLAlchemy Flask?

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() .

Why is SQLAlchemy so slow?

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.

What does SQLAlchemy all () return?

As the documentation says, all() returns the result of the query as a list.


1 Answers

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() }} 
like image 185
Miguel Avatar answered Sep 19 '22 06:09

Miguel