From 98f2b4759c9a7c7ac5e790727d47f2b328520713 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Lafr=C3=A9choux?= Date: Thu, 19 Apr 2018 17:00:40 +0200 Subject: [PATCH] Don't serialize any field if only is empty. Fixes #772 --- marshmallow/schema.py | 6 +++--- tests/test_schema.py | 6 ++++++ 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/marshmallow/schema.py b/marshmallow/schema.py index 5c059cc8e..3abff1f46 100644 --- a/marshmallow/schema.py +++ b/marshmallow/schema.py @@ -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 @@ -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. @@ -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) diff --git a/tests/test_schema.py b/tests/test_schema.py index 73be706a0..5530b40c7 100755 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -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):