speed up cars count query

This commit is contained in:
qananasikq
2026-04-17 23:50:40 +03:00
parent bc5c3698c3
commit ec49ed9bc5

View File

@@ -26,21 +26,28 @@ def list_cars(
# Список автомобилей с пагинацией и фильтрами # Список автомобилей с пагинацией и фильтрами
with persistence.session_scope() as session: with persistence.session_scope() as session:
query = select(Car) query = select(Car)
count_query = select(func.count(Car.id))
if brand: if brand:
escaped_brand = brand.replace("%", r"\%").replace("_", r"\_") escaped_brand = brand.replace("%", r"\%").replace("_", r"\_")
query = query.where(Car.brand.ilike(f"%{escaped_brand}%", escape="\\")) cond = Car.brand.ilike(f"%{escaped_brand}%", escape="\\")
query = query.where(cond)
count_query = count_query.where(cond)
if model: if model:
escaped_model = model.replace("%", r"\%").replace("_", r"\_") escaped_model = model.replace("%", r"\%").replace("_", r"\_")
query = query.where(Car.model.ilike(f"%{escaped_model}%", escape="\\")) cond = Car.model.ilike(f"%{escaped_model}%", escape="\\")
query = query.where(cond)
count_query = count_query.where(cond)
if year_min is not None: if year_min is not None:
query = query.where(Car.year >= year_min) query = query.where(Car.year >= year_min)
count_query = count_query.where(Car.year >= year_min)
if year_max is not None: if year_max is not None:
query = query.where(Car.year <= year_max) query = query.where(Car.year <= year_max)
count_query = count_query.where(Car.year <= year_max)
if is_sold is not None: if is_sold is not None:
query = query.where(Car.is_sold == is_sold) query = query.where(Car.is_sold == is_sold)
count_query = count_query.where(Car.is_sold == is_sold)
count_query = select(func.count()).select_from(query.subquery())
total = session.execute(count_query).scalar() or 0 total = session.execute(count_query).scalar() or 0
offset = (page - 1) * per_page offset = (page - 1) * per_page