0

我有一个关于烧瓶棉花糖模式的问题。所以,我像下面的例子一样创建模型。

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"}

在我倾倒之后?谢谢之前

4

1 回答 1

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
于 2020-07-20T02:00:04.927 回答