Search code examples
pythonmarshmallow

how can I create a dynamic marshmallow field (aka change the fields used for serialization programmatically)?


Let's say that I have two models and two serializers:

class AuthorSchema(ma.ModelSchema):
    class Meta:
        model = Author
        fields = ('id', 'name')


class BookSchema(ma.ModelSchema):
    class Meta:
        model = Book
        authors = fields.Nested(AuthorSchema, many=True)
        fields = ('id', 'title', 'authors')

I'm trying to create some API where the user could both require a book and a book + its authors.

The real situation is much more complex and the user should be able to require a book + a lot of other fields, so creating multiple schemas is not really an option.

How can I create a model that is flexible and where the fields (in this case nested fields) can be added programmatically?


Solution

  • When instantiating a serializer, you can specify exactly what fields are needed for that particular case using the only or include.

    For example, if you wanted to serialize only a book's id and title, you could do something like this:

    schema = BookSchema(only=('id', 'title'))

    or using exclude:

    schema = BookSchema(exclude=('authors',))

    Docs: https://marshmallow.readthedocs.io/en/latest/api_reference.html#schema