Skip to content

Commit

Permalink
Don't serialize any field if only is empty.
Browse files Browse the repository at this point in the history
Fixes #772
  • Loading branch information
lafrech committed Apr 24, 2018
1 parent 07cebb9 commit 98f2b47
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
6 changes: 3 additions & 3 deletions marshmallow/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ class Meta:
"""
pass

def __init__(self, extra=None, only=(), exclude=(), prefix='', strict=None,
def __init__(self, extra=None, only=None, exclude=(), prefix='', strict=None,
many=False, context=None, load_only=(), dump_only=(),
partial=False):
# copy declared fields from metaclass
Expand Down Expand Up @@ -704,7 +704,7 @@ def _do_load(self, data, many=None, partial=None, postprocess=True):

def _normalize_nested_options(self):
"""Apply then flatten nested schema options"""
if self.only:
if self.only is not None:
# Apply the only option to nested fields.
self.__apply_nested_option('only', self.only)
# Remove the child field names from the only option.
Expand Down Expand Up @@ -737,7 +737,7 @@ def __apply_nested_option(self, option_name, field_names):

def _update_fields(self, obj=None, many=False):
"""Update fields based on the passed in object."""
if self.only:
if self.only is not None:
# Return only fields specified in only option
if self.opts.fields:
field_names = self.set_class(self.opts.fields) & self.set_class(self.only)
Expand Down
6 changes: 6 additions & 0 deletions tests/test_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -1066,6 +1066,12 @@ class Meta:
sch = MySchema(only=('baz', ))
assert sch.dump({'foo': 42}).data == {}

def test_only_empty():
class MySchema(Schema):
foo = fields.Field()

sch = MySchema(only=())
assert 'foo' not in sch.dump({'foo': 'bar'})

def test_nested_only_and_exclude():
class Inner(Schema):
Expand Down

0 comments on commit 98f2b47

Please sign in to comment.