how to serialise a enum property in sqlalchemy using marshmallow

蹲街弑〆低调 提交于 2020-11-28 04:54:21

问题


this is my model class

class Type(enum.Enum):
    Certified = "certified"
    Non_Certified = "non-certified"


class Status(enum.Enum):
    Approved = "Approved"
    Rejected = "Rejected"
    Published = "Published"
    Retired = "Retired"
    Waiting_for_Approval = "Waiting_for_Approval"


class DifficultyLevel(enum.Enum):
    Beginner = "Beginner"
    Intermediate = "Intermediate"
    Advanced = "Advanced"
    All = "All"


class ActiveStatus(enum.Enum):
    Archive = "archive"
    Restore = "restore"


class Course(Base):
    __tablename__ = 'course'
    id = Column(Integer, primary_key=True)
    course_code = Column(String(255))
    duration_in_hours = Column(Integer)
    default_eb_price = Column(Integer)
    modified_by = Column(Integer)
    modified_on = Column(DateTime)
    created_by = Column(Integer)
    created_at = Column(DateTime)
    type = Column(Enum(Type))
    certification_vendor = Column(String(255))
    certification_name = Column(String(255))
    micro_training_sessions = Column(Integer)
    status = Column(Enum(Status))
    title = Column(String(255))
    summary = Column(String(255))
    duration = Column(JSON)
    # Categories =
    delivery_language = Column(String(255))
    course_logo = Column(String(255))
    promo_video = Column(String(255))
    overview = Column(String(255))
    objectives = Column(String(255))
    suggested_attendees = Column(String(255))
    prerequisites = Column(String(255))
    difficulty_level = Column(Enum(DifficultyLevel))
    course_facts = Column(JSON)
    price = Column(String(255))
    list_price = Column(String(255))
    early_bird_price = Column(String(255))
    next_recommended_course = Column(postgresql.ARRAY(Integer))
    specialization_paths = Column(postgresql.ARRAY(Integer))
    active_status = Column(Enum(ActiveStatus))

    def __getitem__(self, item):
        return getattr(self, item)

    @property
    def serialize(self):
        """Return object data in easily serializeable format"""
        serialized_obj = {}
        for column in self.__table__.columns:
            serialized_obj[column.key] = self[column.key]
        return serialized_obj

and this the controller function to edit the change

def update_course_ctrl(obj,course_id):
    args = request.args
    course_schema = CourseSchema()
    if args is not None :
        if args['action'] == "archive":
            course = session.query(Course).filter_by(id=course_id).one()
            course.active_status = 'Archive'
            session.merge(course)
            session.commit()
            dump_data = course_schema.dump(course).data
            return dump_data
            # code to archive course
        if args['action'] == "restore":
            course = session.query(Course).filter_by(id=course_id).one()
            course.active_status = 'Restore'
            session.merge(course)
            session.commit()
            dump_data = course_schema.dump(course).data
            return dump_data
    course = Course(**obj.json)
    session.merge(course)
    session.commit()
    dump_data = course_schema.dump(course).data
    return dump_data

this is my code in marshmallow file

from marshmallow_sqlalchemy import ModelSchema
from sqlalchemy.orm import sessionmaker
from app.extensions import engine
from app.course.models import Course, Project, Topic, Resource


DBSession = sessionmaker(bind=engine)
session = DBSession()


class CourseSchema(ModelSchema):
    class Meta:
        model = Course
        sqla_session = session

while calling this update function I am getting this error TypeError: <ActiveStatus.Archive: 'archive'> is not JSON serializable


回答1:


For enum fields, the simplest approach is to install the package called marshmallow_enum via pip (pip install marshmallow_enum), importing it in your project and then in your marshmallow schema definitions override the SQLAlchemy fields with your custom definition:

from marshmallow_enum import EnumField
...


class CourseSchema(ModelSchema):
    type = EnumField(Type, by_value=True)

    class Meta:
        model = Course
        sqla_session = session

All fields that weren't overridden by your custom definitions will be taken from your model.

You can experiment with the by_value parameter, which enables you to either serialize names (by default) or values (by_value=True) of your enums.




回答2:


Another alternative is to override the __str__ method of your Enum. E.g.

class Type(enum.Enum):
    Certified = "certified"
    Non_Certified = "non-certified"

    def __str__(self):
        return self.value



回答3:


You can use Marshmallow custom method fields

from marshmallow import fields

class CourseSchema(ModelSchema):
    type = fields.Method("get_course_type")

    def get_course_type(self, obj):
        return obj.type.value

    class Meta:
        model = Course
        sqla_session = session


来源:https://stackoverflow.com/questions/44717768/how-to-serialise-a-enum-property-in-sqlalchemy-using-marshmallow

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!