How to use marshmallow to serialize a custom sqlalchemy field?

后端 未结 2 1851
盖世英雄少女心
盖世英雄少女心 2021-01-05 23:44

I just start a simple project called flask_wiki this days and I\'m using some flask extensions as the follows:

  • Flask-SQLAlchemy
  • Flask-Restful
相关标签:
2条回答
  • 2021-01-06 00:14

    You need to create your own Converter. Try something like this:

    import uuid
    from flask_wiki.backend.models import Page
    from flask_wiki.backend.backend import marsh
    from marshmallow_sqlalchemy.convert import ModelConverter
    from flask_wiki.backend.custom_fields import GUIDField
    from marshmallow import fields
    
    
    #Here you are overwriting the list of types of the SQLAlchemy, adding your custom type 
    class GUIDConverter(ModelConverter):
        SQLA_TYPE_MAPPING = dict(
            list(ModelConverter.SQLA_TYPE_MAPPING.items()) + 
            [(GUIDField, fields.Str)] 
        )
    
    class GUIDSerializationField(fields.Field):
        def _serialize(self, value, attr, obj):
            if value is None:
                return value
            else:
                if isinstance(value, uuid.UUID):
                    return str(value)
                else:
                    return None
    
    class PageSchema(marsh.ModelSchema):
        class Meta:
            model = Page        
            model_converter = GUIDConverter #Tell to Marshmallow to use your custom converter for this model
    
        guid = GUIDSerializationField(attribute="guid")
    

    You can also see this link for help. I hope it helped and sorry for my bad english

    0 讨论(0)
  • 2021-01-06 00:14

    According to what I've read in the docs, you can specify a model_converter attribute in your ModelSchema Meta class. The ModelConverter class has a SQLA_TYPE_MAPPING attribute you can override in a subclass to add your custom GUID field to the types detected by the automatic schema generator.

    That said, I've never used it so I don't know if this will work or not.

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