Define fields programmatically in Marshmallow Schema

后端 未结 4 594
不思量自难忘°
不思量自难忘° 2021-02-09 05:27

Say I have a Schema like this:

class MySchema(Schema):

    field_1 = Float()
    field_2 = Float()
    ...
    field_42 = Float()

Is there a w

4条回答
  •  轮回少年
    2021-02-09 06:12

    All you need to do is to use type() function to build your class with any attributes you want:

    MySchema = type('MySchema', (marshmallow.Schema,), {
        attr: marshmallow.fields.Float()
        for attr in FIELDS
    })
    

    You can even have different types of fields there:

    fields = {}
    fields['foo'] = marshmallow.fields.Float()
    fields['bar'] = marshmallow.fields.String()
    MySchema = type('MySchema', (marshmallow.Schema,), fields)
    

    or as a base for your customizations:

    class MySchema(type('_MySchema', (marshmallow.Schema,), fields)):
        @marshmallow.post_dump
        def update_something(self, data):
            pass
    

提交回复
热议问题