marshmallow-oneofschema icon indicating copy to clipboard operation
marshmallow-oneofschema copied to clipboard

It's hard to use a parent schema's data to control a Nested OneOfSchema

Open juledwar opened this issue 6 months ago • 3 comments

I have a schema that uses fields.Nested on a OneOfSchema type schema, where the type field data comes from the parent. I can work around the lack of built-in way to do that with some context, and override get_obj_type / get_data_type.

The new way of doing context in Marshmallow v4 has turned this into a much harder endeavour. I've had to override the load method in the parent schema so I can set a contextvar once per item in the incoming list of data which is now picked up by the nested schema's get_xxx methods.

I'm not really sure if there's any easier way to do it but leaving this Issue here in case someone has already thought about it.

juledwar avatar May 12 '25 03:05 juledwar

Maybe the parent schema itself is polymorphic. It contains the type field and differs by which schema is nested in it.

I hope I'm making sense.

lafrech avatar May 12 '25 14:05 lafrech

From what you are saying it sounds like a use case that was not intended. The reason I implemented it this way is because the parent schema is quite large and there's only one field that changes but perhaps I could rewrite it to use inheritance instead.

Thank you.

juledwar avatar May 12 '25 22:05 juledwar

To more accurately describe the use case of what I am doing, it's receiving a json document from an external API and one of the sub-field's schema changes depending on the type field. This isn't particularly polymorphic.

juledwar avatar May 12 '25 22:05 juledwar

@juledwar I think what you're describing here is closer to a polyfield than a polymorphic schema (i.e. the "pivot"/type field lives on the parent schema, and the polymorphic data lives inside another field on that parent schema). There's another library that is built for this purpose, but it hasn't been updated in a while, and no longer seems to work with Marshmallow 4: https://github.com/Bachmann1234/marshmallow-polyfield.

tsokalski avatar Jun 26 '25 19:06 tsokalski

@juledwar I think what you're describing here is closer to a polyfield than a polymorphic schema (i.e. the "pivot"/type field lives on the parent schema, and the polymorphic data lives inside another field on that parent schema). There's another library that is built for this purpose, but it hasn't been updated in a while, and no longer seems to work with Marshmallow 4: https://github.com/Bachmann1234/marshmallow-polyfield.

Thank you.

I think I came across that project when I was investigating solutions to my problem and decided against it purely on the basis that it seemed unmaintained, as you say.

juledwar avatar Jun 26 '25 22:06 juledwar