marshmallow-code / marshmallow-code/marshmallow
Add a "default_dump_fields" or similar parameter to the schema definition
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 7.2k
- Forks
- 738
- Avg merge
- 1d 23h
- Merged PRs (30d)
- 7
Description
Hello all,
I've got a use case which seems like it would be pretty common, but isn't really documented. There are a lot of cases where it is helpful to return only a subset of fields _almost_ every time a schema is used, but allow for occasional extras/overrides. This allows for some nicer reusability.
The code I use to accomplish this functionality is below (adapted from my original, untested):
```python
# Class that allows defaults
class SQLASchemaAdapted(Schema):
"""Allow setting default_fields"""
def __init__(
self, *args, include: list = None, use_defaults: bool = True, **kwargs
):
"""
:param include: list of items to include
:param use_defaults: Use the default_fields, otherwise ignore (i.e. use all)"""
if kwargs.get("only") is None and use_defaults:
_default_fields = getattr(self.Meta, "default_fields", None)
_only = copy.deepcopy(_default_fields) if _default_fields else []
if include:
for i in [inc for inc in include if inc not in _only]:
_only.append(i)
if len(_only) > 0:
kwargs["only"] = tuple(_only)
super().__init__(*args, **kwargs)
# Schema definition just needs default_fields set
class MySchema(SQLASchemaAdapted):
field_a = fields.Str()
field_b = fields.Str()
field_x = fields.Str()
field_y = fields.Str()
field_z = fields.Str()
default_fields = ['field_a', 'field_b']
# Return object with only field_a, field_b, by default
MySchema().dump(obj)
# Return with fields a,b,x,y
MySchema(include=['field_x, 'field_y']).dump(obj)
# Override defaults with "only"
MySchema(only=['field_a']).dump(obj)
# Just do what Marshmallow does by default
MySchema(use_defaults=False).dump(obj)
```
It's possible this functionality already exists somehow that I just missed, in which case I'm happy to see this issue closed. If not, however, it's a pretty simple implementation that could fit nice in Marshmallow core.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the Schema initialization path and the existing handling of only, then compare the proposed default_fields, include, use_defaults, and only interactions. Done means schemas can select default fields while allowing extras, explicit overrides, and the current all-fields behavior when defaults are disabled.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend-api-design
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100