home · contact · privacy
Refactor saving and caching tests, treatment of None IDs.
[plomtask] / plomtask / db.py
index f6ef1cb6724a4a8cb13cc3d74d8c745338294463..797b08e8412809e3ac23bb7f04fc24fef955be03 100644 (file)
@@ -388,9 +388,7 @@ class BaseModel(Generic[BaseModelId]):
         return obj
 
     @classmethod
-    def by_id(cls, db_conn: DatabaseConnection,
-              id_: BaseModelId | None
-              ) -> Self:
+    def by_id(cls, db_conn: DatabaseConnection, id_: BaseModelId) -> Self:
         """Retrieve by id_, on failure throw NotFoundException.
 
         First try to get from cls.cache_, only then check DB; if found,
@@ -414,11 +412,12 @@ class BaseModel(Generic[BaseModelId]):
         """Wrapper around .by_id, creating (not caching/saving) if not find."""
         if not cls.can_create_by_id:
             raise HandledException('Class cannot .by_id_or_create.')
+        if id_ is None:
+            return cls(None)
         try:
             return cls.by_id(db_conn, id_)
         except NotFoundException:
-            obj = cls(id_)
-            return obj
+            return cls(id_)
 
     @classmethod
     def all(cls: type[BaseModelInstance],