Improve "get_collection_count" method

This improvement is based on [1]. "get_collection_count" can now
request a model query requesting only one single field from the
model. That simplifies the SQL query and improves the performance.
The result provided will have the same number of elements; that
means the result of the collection count will be the same.

[1]https://review.opendev.org/c/openstack/neutron-lib/+/787672

Closes-Bug: #1942863

Change-Id: Ie0bffac20b9c40933b64f163de3cc03d45b24682
This commit is contained in:
Rodolfo Alonso Hernandez 2021-09-07 08:37:53 +00:00
parent 670f83b0de
commit 64e4dc29a4

View File

@ -344,12 +344,16 @@ def get_values(context, model, field, filters=None):
return [c[0] for c in query]
def get_collection_count(context, model, filters=None):
def get_collection_count(context, model, filters=None, query_field=None):
"""Get the count for a specific collection.
:param context: The context to use for the DB session.
:param model: The model for the query.
:param filters: The filters to apply.
:param query_field: Column, in string format, from the "model"; the query
will return only this parameter instead of the full
model columns.
:returns: The number of objects for said model with filters applied.
"""
return get_collection_query(context, model, filters).count()
return get_collection_query(context, model, filters=filters,
field=query_field).count()