Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Many Option #2271

Merged
merged 1 commit into from
Aug 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"}