freeze¶
You can use the freeze
clause with any query type.
Source¶
- Query.freeze() FrozenQuery ¶
This is a performance optimisation when the same query is run repeatedly. For example:
TOP_BANDS = Band.select( Band.name ).order_by( Band.popularity, ascending=False ).limit( 10 ).output( as_json=True ).freeze() # In the corresponding view/endpoint of whichever web framework # you're using: async def top_bands(self, request): return await TOP_BANDS
It means that Piccolo doesn’t have to work as hard each time the query is run to generate the corresponding SQL - some of it is cached. If the query is defined within the view/endpoint, it has to generate the SQL from scratch each time.
Once a query is frozen, you can’t apply any more clauses to it (
where
,limit
,output
etc).Even though
freeze
helps with performance, there are limits to how much it can help, as most of the time is still spent waiting for a response from the database. However, for high throughput apps and data science scripts, it’s a worthwhile optimisation.