Marshmallow: How Nested Fields Dynamically Set Schema?

Created on 26 Feb 2019  ·  3Comments  ·  Source: marshmallow-code/marshmallow

Hi,
I have a question.

class PaginationSchema:
items = fields.Nested('schema_name', many = True, dump_only = True)
count = fields.Integer()
page = fields.Integer()

'schema_name' is dynamically incoming.
I don't know what to do. i need help
Thanks!

question

Most helpful comment

It sounds like you need a function to dynamically declare the schema class. You probably don't need to use the schema name / schema registry. Simply passing in the schema class to the function should work. The schema registry is mainly needed for circular/self-referencing schema.

https://marshmallow.readthedocs.io/en/latest/nesting.html#nesting-schemas

def paginate_schema(schema):
    class PaginationSchema(Schema):
        items = fields.Nested(schema, many = True, dump_only = True)
        ...
    return PaginationSchema

This pattern also works nicely as a decorator.

All 3 comments

It sounds like you need a function to dynamically declare the schema class. You probably don't need to use the schema name / schema registry. Simply passing in the schema class to the function should work. The schema registry is mainly needed for circular/self-referencing schema.

https://marshmallow.readthedocs.io/en/latest/nesting.html#nesting-schemas

def paginate_schema(schema):
    class PaginationSchema(Schema):
        items = fields.Nested(schema, many = True, dump_only = True)
        ...
    return PaginationSchema

This pattern also works nicely as a decorator.

It sounds like you need a function to dynamically declare the schema class. You probably don't need to use the schema name / schema registry. Simply passing in the schema class to the function should work. The schema registry is mainly needed for circular/self-referencing schema.

https://marshmallow.readthedocs.io/en/latest/nesting.html#nesting-schemas

def paginate_schema(schema):
    class PaginationSchema(Schema):
        items = fields.Nested(schema, many = True, dump_only = True)
        ...
    return PaginationSchema

This pattern also works nicely as a decorator.

This good . i want to know what should i do.

i want to know what should i do.

I'm not sure if this is a question. If you need anything else, feel free to continue the discussion here. I am closing this issue for now since you seem to indicate that your original question has been answered.

Was this page helpful?
0 / 5 - 0 ratings