Skip to content

Commit

Permalink
Merge pull request #2271 from deckar01/2270-meta-many
Browse files Browse the repository at this point in the history
Many Option
  • Loading branch information
lafrech authored Aug 20, 2024
2 parents 7609530 + c8ce7e8 commit 78cbc09
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
6 changes: 4 additions & 2 deletions src/marshmallow/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,7 @@ def __init__(self, meta, ordered: bool = False):
self.dump_only = getattr(meta, "dump_only", ())
self.unknown = validate_unknown_parameter_value(getattr(meta, "unknown", RAISE))
self.register = getattr(meta, "register", True)
self.many = getattr(meta, "many", False)


class Schema(base.SchemaABC, metaclass=SchemaMeta):
Expand Down Expand Up @@ -344,6 +345,7 @@ class Meta:
`OrderedDict`.
- ``exclude``: Tuple or list of fields to exclude in the serialized result.
Nested fields can be represented with dot delimiters.
- ``many``: Whether the data is a collection by default.
- ``dateformat``: Default format for `Date <fields.Date>` fields.
- ``datetimeformat``: Default format for `DateTime <fields.DateTime>` fields.
- ``timeformat``: Default format for `Time <fields.Time>` fields.
Expand All @@ -367,7 +369,7 @@ def __init__(
*,
only: types.StrSequenceOrSet | None = None,
exclude: types.StrSequenceOrSet = (),
many: bool = False,
many: bool | None = None,
context: dict | None = None,
load_only: types.StrSequenceOrSet = (),
dump_only: types.StrSequenceOrSet = (),
Expand All @@ -381,7 +383,7 @@ def __init__(
raise StringNotCollectionError('"exclude" should be a list of strings')
# copy declared fields from metaclass
self.declared_fields = copy.deepcopy(self._declared_fields)
self.many = many
self.many = self.opts.many if many is None else many
self.only = only
self.exclude: set[typing.Any] | typing.MutableSet[typing.Any] = set(
self.opts.exclude
Expand Down
16 changes: 16 additions & 0 deletions tests/test_options.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,3 +262,19 @@ class AddFieldsChild(self.AddFieldsSchema):
assert "email" in s._declared_fields.keys()
assert "from" in s._declared_fields.keys()
assert isinstance(s._declared_fields["from"], fields.Str)


class TestManyOption:
class ManySchema(Schema):
foo = fields.Str()

class Meta:
many = True

def test_many_by_default(self):
test = self.ManySchema()
assert test.load([{"foo": "bar"}]) == [{"foo": "bar"}]

def test_explicit_single(self):
test = self.ManySchema(many=False)
assert test.load({"foo": "bar"}) == {"foo": "bar"}

0 comments on commit 78cbc09

Please sign in to comment.