Skip to content

Commit

Permalink
Add a many Meta option
Browse files Browse the repository at this point in the history
  • Loading branch information
deckar01 committed May 24, 2024
1 parent c592536 commit c8ce7e8
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 @@ -227,6 +227,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 @@ -343,6 +344,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 @@ -366,7 +368,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 @@ -380,7 +382,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 c8ce7e8

Please sign in to comment.