如何使用棉花糖在sqlalchemy中序列化枚举属性 [英] how to serialise a enum property in sqlalchemy using marshmallow

查看:130
本文介绍了如何使用棉花糖在sqlalchemy中序列化枚举属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的模型课程

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

在调用此更新函数时,我遇到此错误
TypeError:< ActiveStatus.Archive:'存档'>不是JSON可序列化的

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

推荐答案

对于枚举字段,最简单的方法是安装名为<$ c $的软件包c> marshmallow_enum 通过pip( pip install marshmallow_enum ),将其导入项目,然后在您的棉花糖模式定义中使用自定义覆盖SQLAlchemy字段定义:

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.

您可以尝试使用 by_value 参数,该参数使您可以序列化名称(默认情况下)或值( by_value = True )。

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.

这篇关于如何使用棉花糖在sqlalchemy中序列化枚举属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆