how to serialise a enum property in sqlalchemy using marshmallow

后端 未结 3 1283
感情败类
感情败类 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:22

    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
    
    0 讨论(0)
  • 2021-01-12 02:30

    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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题