marshmallow-code / marshmallow-code/marshmallow

Dumping objects with fields unknown to schema in versions >=3.0.0

Open
#1,545 8 comments 0 reactions 0 assignees View on GitHub
question
Dominant language
Python
Stars
7.2k
Forks
738
Avg merge
1d 23h
Merged PRs (30d)
7

Description

I am trying to serialize an object with some fields additional to that defined in the schema. While dumping, I am also specifying fields to be included using `only`. I was able to specify fields unknown to the schema in the `only ` parameter when I was using version `2.19.5`, but it's breaking when I upgraded to `3.5.1`. For clarity, consider the following code:

```
class MySchema(Schema):
a = fields.Str()
b = fields.Str()
c = fields.Str()

class MyClass:
def __init__(self, a, b, c, d, e):
self.a = a
self.b = b
self.c = c
self.d = d
self.e = e

obj = MyClass("one", "two", "three", "four", "five")

data_out = MySchema(only=('a', 'b', 'c', 'd')).dump(obj)

print(data_out.data)

# Output with 2.19.5 (expected behavior) => {'a': 'one', 'c': 'three', 'b': 'two', 'd': 'four'}
# With 3.5.1 => ValueError: Invalid fields for : {'d'}
```
One solution is to add those unknown fields to the Schema, but I was wondering whether there is a proper workaround for this issue when I am using the newer versions (specifically >=3.0.0).

I feel this is similar to #1198 but I was not able to find a solution for this in the thread.

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the MySchema(only=('a', 'b', 'c', 'd')).dump(obj) example and inspect how Schema validates unknown fields in marshmallow 3.5.1 compared with 2.19.5. Done means identifying the supported workaround or confirming a compatible behavior for fields outside the schema when using only.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend-api-design
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.