X-Git-Url: https://plomlompom.com/repos/foo.html?a=blobdiff_plain;f=plomtask%2Fdb.py;h=13cdaef5b9c7d3e992f8c92730a9979b9eee2d73;hb=a71dbd0fdbc8a03d400c59d0446595a995301d07;hp=71c59d50d8b0013dcf3bd9e6c811080563606830;hpb=244270eed71df45faf9554d0666b816be9876f77;p=plomtask
diff --git a/plomtask/db.py b/plomtask/db.py
index 71c59d5..13cdaef 100644
--- a/plomtask/db.py
+++ b/plomtask/db.py
@@ -4,7 +4,7 @@ from os import listdir
from os.path import isfile
from difflib import Differ
from sqlite3 import connect as sql_connect, Cursor, Row
-from typing import Any, Self, TypeVar, Generic
+from typing import Any, Self, TypeVar, Generic, Callable
from plomtask.exceptions import HandledException, NotFoundException
from plomtask.dating import valid_date
@@ -241,6 +241,7 @@ class BaseModel(Generic[BaseModelId]):
to_search: list[str] = []
can_create_by_id = False
_exists = True
+ sorters: dict[str, Callable[..., Any]] = {}
def __init__(self, id_: BaseModelId | None) -> None:
if isinstance(id_, int) and id_ < 1:
@@ -335,6 +336,22 @@ class BaseModel(Generic[BaseModelId]):
"""Convenience method to return cls' name in lowercase."""
return cls.__name__.lower()
+ @classmethod
+ def sort_by(cls, seq: list[Any], sort_key: str, default: str = 'title'
+ ) -> str:
+ """Sort cls list by cls.sorters[sort_key] (reverse if '-'-prefixed)."""
+ reverse = False
+ if len(sort_key) > 1 and '-' == sort_key[0]:
+ sort_key = sort_key[1:]
+ reverse = True
+ if sort_key not in cls.sorters:
+ sort_key = default
+ sorter: Callable[..., Any] = cls.sorters[sort_key]
+ seq.sort(key=sorter, reverse=reverse)
+ if reverse:
+ sort_key = f'-{sort_key}'
+ return sort_key
+
# cache management
# (we primarily use the cache to ensure we work on the same object in
# memory no matter where and how we retrieve it, e.g. we don't want