Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The default value specified in the field when the value is None #1656

Closed
FRiMN opened this issue Aug 24, 2020 · 3 comments
Closed

The default value specified in the field when the value is None #1656

FRiMN opened this issue Aug 24, 2020 · 3 comments

Comments

@FRiMN
Copy link

FRiMN commented Aug 24, 2020

I have scheme like this:

class NullProcessingSchema(Schema):
    @post_load
    def null_to_default_value(self, data: dict, **kwargs):
        return {
            key: (0 if key == 'field_1' and value is None else value)    # explicit field name
            for key, value in data.items()
        }

class ContentData(NullProcessingSchema):
    field_1 = fields.Int(allow_none=True)
    field_2 = fields.Str(allow_none=True)
    # etc...

I have many fields with different types in ContentData.
I don't want to explicitly list the field names in post_load.

Is there a way to define a default value (when None) in the field itself?
Or is it possible to get the type of a field in post_load?

@lafrech
Copy link
Member

lafrech commented Aug 24, 2020

You can't do that at field level.

You can remove the key == "field_1" condition if all None values should be turned into 0. If the value depends on the field type, it won't work.

A better alternative would be to use a pre_load method to remove None values and use the missing parameter. Then you can remove allow_none=True.

@FRiMN
Copy link
Author

FRiMN commented Aug 24, 2020

The problem is that the fields are present alternatively: either field_1 or field_2, etc.

If you're interested, this is the Amazon Alexa API answer (xml):

<aws:ContentData>
      <aws:DataUrl type="canonical">example.com/</aws:DataUrl>
      <aws:LinksInCount/>    <!-- This field is defined in the API request and can be different -->
</aws:ContentData>

@lafrech
Copy link
Member

lafrech commented Apr 8, 2021

I don't have the whole picture so I can't tell what the best solution would be.

#1381 should provide a nice way to achieve this.

@lafrech lafrech closed this as completed Apr 8, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants