Comments (11)
An update: skipping missing values is now the default behavior in marshmallow 2.0.0: https://marshmallow.readthedocs.org/en/latest/upgrading.html#default-values
For this reason, I think I'm going to go ahead and deprecate the skip_missing
option.
from marshmallow.
- Recursive
class NotNoneSchemaBase:
@post_dump
def clear_none(self, data):
result = {}
for k, v in data.items():
if v is None:
continue
elif isinstance(v, dict):
result[k] = self.clear_none(v)
else:
result[k] = v
return result
from marshmallow.
There is currently no way to skip missing fields during serialization. One simple feature addition would be to allow fields to default to the fields.missing
sentinel value, which would instruct the Schema to skip serialization if the value is missing.
class TestSchema(Schema):
first_name = String()
family_name = String()
age = Integer(default=fields.missing)
Would this meet your use case?
from marshmallow.
Yep, that's a good point which I've missed - currently I am assigning None to default and then filtering is performed manually. Thanks!
from marshmallow.
@malexer The above code snippet was strictly hypothetical and will not work (at the time of this posting). It was merely a proposal so I could get feedback. If you think the above is a good solution, I can move forward with implementing it.
Reopening.
from marshmallow.
This solution is quite good but as for me it is better to add some option on a schema level (class Meta) - the similar way as it is done in schematics with serialize_when_none option.
My case: I have a set of required fields and optional ones. For optional I need to avoid having any default values in case if no such fields are found in the source data. This will need to set default=fields.missing
for every such optional field.
Hope this will help you to come out with a nice solution!
from marshmallow.
I agree that a schema-level option might be useful.. I'll see what I can do with this in the next few days.
from marshmallow.
This behavior has been implemented via the skip_missing
class Meta option.
from marshmallow.
middle_name = fields.String(none=False, required=False)
generates
{'middle_name': None}
from
class C:
pass
c = C()
c.middle_name = None
But I want {}
from marshmallow.
I see several ways to fix that:
- Use marshmallow.fields.Function like this for occasional fields that require to be removed:
import marshmallow as m
import marshmallow.feilds as mf
from marshmallow.utils import missing
class MySchema(m.Schema):
my_field = mf.Function(lambda o: o.my_field or missing)
- Use your own post_dump filter to remove all None values:
class MySchema(m.Schema):
my_field = mf.String()
@m.post_dump
def remove_nones(self, data):
return {k: v for k, v in data.iteritems() if v is not None}
- Make your own wrapper field types to accomodate for that:
class MyString(mf.String):
def _serialize(self, value, attr, obj):
result = super(MyString, self)._serialize(value, attr, obj)
return result if result is not None else missing
class MySchema(m.Schema):
my_field = MyString()
from marshmallow.
Yeah, what I meant for post_dump case is that all schemas (that we care about) have this post_dump hook, so there is no need for recursion.
from marshmallow.
Related Issues (20)
- Address deprecation warnings in tests HOT 1
- URL validation fails if URL is missing user field HOT 5
- fields.URL validation error should specify "not a valid FQDN" if trying to pass hostname without domain
- missing `f` for f-Strings HOT 2
- `fields.Url` does not accept `file` URLs
- when a new request, schema context not reset !!! HOT 2
- Questions about Copilot + Open Source Software Hierarchy HOT 3
- Allow None for a allow_none=True Date field HOT 6
- fields.Nested Type Warning Since Version 3.15.0
- Setting many=True through Meta - SchemaOpts HOT 1
- RFE: use `zoneinfo` instead of `pytz` HOT 3
- 3.21.2: pytest fails in units checking time HOT 1
- 3.21.2: sphinx warnings `reference target not found` HOT 2
- Static typing of Field subclass kwargs
- Help understanding how to set Schema meta options when using Schema.from_dict() HOT 1
- PyRight: Static TypeChecking of `Schema: ClassVar[Type[Schema]] = Schema` fails HOT 1
- Send a post request containing nested data, .List(fields.Nested(Schema)), Flask restapi - marshmallow schema HOT 4
- OSS Fuzz Integration
- Dynamically set data_key in nested field?
- Error when passing custom parameter in Nested schema HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from marshmallow.