how to serialise a enum property in sqlalchemy using marshmallow

后端 未结 3 1286
感情败类
感情败类 2021-01-12 02:01

this is my model class

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


class Status(enum.Enum):
    Approved = \         


        
3条回答
  •  不思量自难忘°
    2021-01-12 02:41

    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.

提交回复
热议问题