CRUDkit fixes and changes.

This commit is contained in:
Yaro Kasear 2025-09-10 09:18:31 -05:00
parent 9d36d600bb
commit 7ddfe084ba
5 changed files with 98 additions and 43 deletions

View file

@ -11,26 +11,37 @@ class CRUDMixin:
def as_dict(self, fields: list[str] | None = None):
"""
Serialize mapped columns. Honors projection if either:
- 'fields' is passed explicitly, or
-
Serialize the instance.
- If 'fields' (possibly dotted) is provided, emit exactly those keys.
- Else, if '__crudkit_projection__' is set on the instance, emit those keys.
- Else, fall back to all mapped columns on this class hierarchy.
Always includes 'id' when present unless explicitly excluded.
"""
allowed = None
if fields is None:
fields = getattr(self, "__crudkit_projection__", None)
if fields:
allowed = set(fields)
else:
allowed = getattr(self, "__crudkit_root_fields__", None)
out = {}
if "id" not in fields and hasattr(self, "id"):
out["id"] = getattr(self, "id")
for f in fields:
cur = self
for part in f.split("."):
if cur is None:
break
cur = getattr(cur, part, None)
out[f] = cur
return out
result = {}
for cls in self.__class__.__mro__:
if not hasattr(cls, "__table__"):
continue
for column in cls.__table__.columns:
name = column.name
if allowed is not None and name not in allowed and name != "id":
continue
result[name] = getattr(self, name)
for cls in self.__clas__.__mro__:
if hasattr(cls, "__table__"):
for column in cls.__table__.columns:
name = column.name
result[name] = getattr(self, name)
return result
class Version(Base):
__tablename__ = "versions"