From 7c4958e0cb1963ac0eb43bafa044747bde2fb729 Mon Sep 17 00:00:00 2001 From: Yaro Kasear Date: Tue, 19 Aug 2025 08:11:05 -0500 Subject: [PATCH] Refactor default_query function to improve readability and add eager loading options --- inventory/ui/defaults.py | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/inventory/ui/defaults.py b/inventory/ui/defaults.py index d01e1c9..10dcee3 100644 --- a/inventory/ui/defaults.py +++ b/inventory/ui/defaults.py @@ -1,8 +1,7 @@ from sqlalchemy import select, asc as sa_asc, desc as sa_desc from sqlalchemy.inspection import inspect from sqlalchemy.sql import Select -from sqlalchemy.orm import Query -from typing import Any, Optional, cast +from typing import Any, Optional, cast, Iterable PREFERRED_LABELS = ("identifier", "name", "first_name", "last_name", "description") @@ -48,15 +47,10 @@ def default_query( """ stmt: Select[Any] = select(Model) - # Optional per-model search hook ui_search = getattr(Model, "ui_search", None) if callable(ui_search) and text: stmt = cast(Select[Any], ui_search(stmt, text)) - # Sorting priority: - # 1. explicit sort param - # 2. per-model ui_sort hook - # 3. per-model ui_order_cols default ordering if sort: ui_sort = getattr(Model, "ui_sort", None) if callable(ui_sort): @@ -78,6 +72,17 @@ def default_query( if limit > 0: stmt = stmt.limit(limit) + opts_attr = getattr(Model, "ui_eagerload", ()) + + opts: Iterable[Any] + if callable(opts_attr): + opts = cast(Iterable[Any], opts_attr()) # if you want, pass Model to it: opts_attr(Model) + else: + opts = cast(Iterable[Any], opts_attr) + + for opt in opts: + stmt = stmt.options(opt) + return list(session.execute(stmt).scalars().all()) def default_create(session, Model, payload):