Skip to content
This repository has been archived by the owner on Oct 19, 2022. It is now read-only.

Allow dump_by to take lambdas #41

Open
kunalbhagawati opened this issue Jul 7, 2020 · 0 comments
Open

Allow dump_by to take lambdas #41

kunalbhagawati opened this issue Jul 7, 2020 · 0 comments

Comments

@kunalbhagawati
Copy link

If we have a field that deserializes to an Enum but serializes from an object with an enum attribute, will it be easier to let the dump_by attribute to be callable?
This will avoid the hassle of creating a Method field with custom serialization and deserialization.

For example,
If the API request body is:

{
  "name": "Some user",
  "role": "PARENT" // enum here
}

and the view builds a user object, where the role is an sqlalchemy enum field (assuming role.label is an enum), then it would need to serialize from role.label.

Right now even subclassing wont work since __init__ raises a validation error:

class FromObjectEnumField(EnumField):
    def _serialize(self, value, attr, obj):
        if callable(self.dump_by):
            value = self.dump_by(value)
        return super()._serialize(value, attr, obj)

# raises `ValueError: Invalid selection for load_by must be EnumField.VALUE or EnumField.NAME, got <function UserSchema.<lambda> at 0x10c8ce040>` on `__init__`

Forcing me to override init as well. Is there a better way to handle this?


marshmallow-enum==1.5.1

@kunalbhagawati kunalbhagawati changed the title Allow dump_by to allow lambdas Allow dump_by to take lambdas Jul 7, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant