用烧瓶棉花糖模式解析枚举输出

时间:2020-07-10 21:42:50

标签: python schema dump flask-marshmallow marshmallow-sqlalchemy

我对烧瓶蛋白软糖模式有疑问。因此,我像下面的示例一样创建模型。

class ID(db.Model):
    __abstract__ = True

    id = db.Column(db.Integer, autoincrement=True, primary_key=True)


class Timestamp(db.Model):
    __abstract__ = True

    created = db.Column(db.DateTime, default=db.func.now(), nullable=False)
    updated = db.Column(


class Checklist(ID, Timestamp):
    __tablename__ = "checklist"

    partner_id = db.Column(db.Integer(), db.ForeignKey("partner.id"), nullable=False)
    statement_status = db.Column(
        db.Enum(StatementStatus), nullable=False, default=StatementStatus.NOT_SELECTED
    )
    statement_accuracy = db.Column(
        db.Enum(StatementAccuracy),
        nullable=False,
        default=StatementAccuracy.NOT_SELECTED,
    )
    update_status = db.Column(
        db.Enum(UpdateStatus), nullable=False, default=UpdateStatus.NOT_SELECTED
    )
    annual_text_return = db.Column(
        db.Enum(AnnualReturnStatus),
        nullable=False,
        default=AnnualReturnStatus.NOT_SELECTED,
    )

然后我有这样的架构:

from flask_marshmallow.sqla import SQLAlchemyAutoSchema
class ChecklistSchema(SQLAlchemyAutoSchema):

class Meta:
    model = Checklist
    include_fk = True

是否可以像这样输出枚举

statement_status: {"value": NOT_SELECTED, "name": "Not Selected"}

我转储后?在此之前

1 个答案:

答案 0 :(得分:0)

最后我找到了答案。

  1. 创建将字段枚举序列化为dict的类

    EnumToDictionary(fields.Field)类:

def _serialize(self, value, attr, obj, **kwargs):
    if value is None:
        return None
    return {"name": value.name, "value": value.value}
  1. 使用课程
class ChecklistSchema(SQLAlchemyAutoSchema):
statement_status = EnumToDictionary(attribute=("statement_status"))
statement_accuracy = EnumToDictionary(attribute="statement_accuracy")
update_status = EnumToDictionary(attribute="update_status")
annual_text_return = EnumToDictionary(attribute="annual_text_return")

class Meta:
    model = Checklist
    include_fk = True