-
-
Notifications
You must be signed in to change notification settings - Fork 628
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
Bug: Fields items are serialized more than once by fields.Method #1995
Comments
I'd say the error lies in container fields such as def _serialize(self, value, attr, obj, **kwargs) -> list[typing.Any] | None:
if value is None:
return None
return [self.inner._serialize(each, attr, obj, **kwargs) for each in value] When serializing a list, This is related to #2039. I don't see a nice solution to this. In fact, what I say in #2039 is that we shouldn't pass Thanks for adding another example of why this design is wrong, but I can't think of a better implementation. (Sorry I didn't get the time to further look into #1993 and #1994.) |
i think the current behavior is actually the expected behavior of that said, this isn't the intended usage for from dataclasses import dataclass
from marshmallow import Schema, fields
@dataclass
class Book:
name: str
@dataclass
class Author:
books: list[Book]
class BookSchema(Schema):
name = fields.String()
class AuthorSchema(Schema):
upper_book_names = fields.Method("get_book_names")
def get_book_names(self, author: Author):
return [book.name.upper() for book in author.books]
author = Author(books=[Book(name="Book1"), Book(name="Book2")])
schema = AuthorSchema()
dumped = schema.dump(author)
# {
# "upper_book_names": [
# "BOOK1",
# "BOOK2",
# ],
# } this a bit of a contrived example though. the above use case is better solved with def uppercase(value):
return value.upper()
class AuthorSchema(Schema):
upper_book_names = fields.List(
fields.Pluck(BookSchema(), "name"), attribute="books", post_dump=(uppercase,)
) |
After fixing #1993 in #1994, I stumbled upon another bug. List items are serialized more than once by
fields.Method
. To reproduce the bug, let's have the following Schema:Let's have the following serialization code:
After serialization
dumped
will beinstead of
The cause of the problem is, the
serialize_me
method never receives the value that should be serialized (neither as an argument, nor in**kwargs
), it only gets theobj
that is being serialized. By looking at the source code here, we see that the_serialize_method
offields.Method
does not get thevalue
as parameter.Although the fix seems to be quite simple, just pass the
value
to the_serialize_method
, it would be a breaking API change that would need a new major release.To avoid a new major release, I would like to ask the maintainer(s) of the repository if they see any other solution to fix this bug?
The text was updated successfully, but these errors were encountered: