Files
FastapiAdmin/backend/app/core/serializers.py
T
zhangtao e159b31e62 feat: Add role code to system_role.json and update system_users.json creator_id to null
fix: Refactor initialize.py to handle nested children data during initialization

feat: Implement tree structure traversal functions in common_util.py

chore: Update requirements.txt to specify sqlalchemy-crud-plus version and add rich

refactor: Change API endpoints in dept.ts and menu.ts to return tree structure

feat: Add code field to role, dept, and menu interfaces in respective TypeScript files

fix: Update dept and role Vue components to display and handle code field

docs: Add comprehensive project documentation for FastAPI Vue3 Admin
2025-09-15 00:19:11 +08:00

63 lines
1.7 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from decimal import Decimal
from typing import Any, Sequence, TypeVar
from fastapi.encoders import decimal_encoder
from sqlalchemy import Row, RowMapping
from sqlalchemy.orm import ColumnProperty, SynonymProperty, class_mapper
RowData = Row | RowMapping | Any
R = TypeVar('R', bound=RowData)
def select_columns_serialize(row: R) -> dict[str, Any]:
"""
序列化 SQLAlchemy 查询表的列,不包含关联列
:param row: SQLAlchemy 查询结果行
:return:
"""
result = {}
for column in row.__table__.columns.keys():
value = getattr(row, column)
if isinstance(value, Decimal):
value = decimal_encoder(value)
result[column] = value
return result
def select_list_serialize(row: Sequence[R]) -> list[dict[str, Any]]:
"""
序列化 SQLAlchemy 查询列表
:param row: SQLAlchemy 查询结果列表
:return:
"""
return [select_columns_serialize(item) for item in row]
def select_as_dict(row: R, use_alias: bool = False) -> dict[str, Any]:
"""
将 SQLAlchemy 查询结果转换为字典,可以包含关联数据
:param row: SQLAlchemy 查询结果行
:param use_alias: 是否使用别名作为列名
:return:
"""
if not use_alias:
result = row.__dict__
if '_sa_instance_state' in result:
del result['_sa_instance_state']
else:
result = {}
mapper = class_mapper(row.__class__) # type: ignore
for prop in mapper.iterate_properties:
if isinstance(prop, (ColumnProperty, SynonymProperty)):
key = prop.key
result[key] = getattr(row, key)
return result