简体   繁体   中英

Parse Enum Output with Flask Marshmallow Schema

I have a question about flask marshmallow schema. So, I create models like an example below.

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,
    )

Then i have schema like this:

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

class Meta:
    model = Checklist
    include_fk = True

Is it possible to have output enum like

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

after I dump? Thx before

Finally I found the answer.

  1. create class that serialize field enum to dict

    class EnumToDictionary(fields.Field):

 def _serialize(self, value, attr, obj, **kwargs): if value is None: return None return {"name": value.name, "value": value.value}
  1. use the class
 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM