我使用的是烧瓶棉花糖 0.13.0
我创建了一个继承自 db.Models 的表
from api import db # SQLAlchemy
class User(db.Model):
__tablename__ = "users"
__table_args__ = {"mysql_engine": "InnoDB",
"mysql_row_format": "DYNAMIC",
"mysql_charset": "utf8"}
id = Column(types.INTEGER, primary_key=True, autoincrement=True)
name = Column(types.String(36), nullable=False)
age = Column(types.String(20), nullable=True)
created_on = Column(types.DATETIME, nullable=False,
default=func.current_timestamp())
枚举定义为
class Age(enum.Enum):
Infant = "infant"
Teenager = "teenager"
Adult = "adult"
架构定义为:
class UserSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = User
load_only = ("id", "created_on",) # exclude these attributes when converting to Json
dump_only = ("id",)
load_instance = True
当我将从数据库中检索到的行反序列化为 User 对象时,我想将 age
属性转换为枚举而不是字符串(在 db 中存储为字符串)
当前的实现将按原样反序列化数据。有没有办法在反序列化过程中实现类型转换?
在将其发布到此处之前,我确实查阅了大量文档以获得解决方案。
https://marshmallow.readthedocs.io/en/stable/api_reference.html#marshmallow.Schema.on_bind_field