serialize.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. """多租户:为 API 出参写入嵌套 ``tenant``(需 ORM 已加载 tenant 关系或仅有 tenant_id)。"""
  2. from __future__ import annotations
  3. from typing import Any, TypeVar
  4. from pydantic import BaseModel
  5. TOut = TypeVar("TOut", bound=BaseModel)
  6. def enrich_tenant_fields(obj: Any, data: dict[str, Any]) -> dict[str, Any]:
  7. """
  8. 合并已有序列化结果,并写入嵌套 ``tenant``;去掉扁平的 tenant_* 字段。
  9. 参数:
  10. - obj: 带 ``tenant_id``、可选 ``tenant`` 关系的 ORM 实例。
  11. - data: 已 ``model_dump()`` 的字典。
  12. 返回:
  13. - dict: 含 ``tenant: { id, name, code } | None``。
  14. """
  15. out = dict(data)
  16. out.pop("tenant_id", None)
  17. out.pop("tenant_name", None)
  18. out.pop("tenant_code", None)
  19. tid = getattr(obj, "tenant_id", None)
  20. t = getattr(obj, "tenant", None)
  21. if t is not None:
  22. out["tenant"] = {
  23. "id": getattr(t, "id", tid),
  24. "name": getattr(t, "name", None),
  25. "code": getattr(t, "code", None),
  26. }
  27. elif tid is not None:
  28. out["tenant"] = {"id": tid, "name": None, "code": None}
  29. else:
  30. out["tenant"] = None
  31. return out
  32. def dump_out_with_tenant(schema: type[TOut], obj: Any) -> dict[str, Any]:
  33. """将 ORM ``obj`` 用 ``schema`` 校验后 ``model_dump``,再合并租户展示字段。"""
  34. return enrich_tenant_fields(obj, schema.model_validate(obj).model_dump())