Using the same attribute twice does not seem to work even with dump_only=True on a Nested field
aphilas opened this issue · 0 comments
I intend to use the same schema for loading and dumping. An example structure for this use case is: Author -< Book
Loading
AuthorSchema field: books = RelatedList(Related(), attribute='books')
AuthorSchema().load({ 'books': [ 1, 2 ] }) # {'books': [<Book>, <Book> ] }
✅
Dumping
AuthorSchema field: books = Nested('BookSchema')
AuthorSchema().dump(Author.query.get(1)) # {'books': {'id': 1, 'title': 'Lorem ipsum' }}
✅
Both
Having books = RelatedList(Related(), attribute='books')
and books_list = Nested('BookSchema', dump_only=True)
as explained in marshmallow-code/marshmallow#1038, works for loading but not for dumping. Should the field have the same name as the attribute? If so that would make it impossible for both to exist simultaneously.
However using Pluck as in marshmallow-code/marshmallow#1038 gives the desired effect, only it would be tedious to replicate for all fields.
I might have an incomplete idea of how marshmallow/marshmallow-sqlalchemy works, so please feel free to elaborate, or to ask for further clarification on my specific use case.
Addendum:
I've noticed that in the case where you'd want to load a new Author
as well as new nested Book
s e.g. AuthorSchema().load({ books: [{ 'title': 'My new book' }]})
(as show in this SO questions) you need the Nested field.
ETA: change example to more popular Author/Books model