Fastapi: Get response_model class as a result of a callable

Created on 7 Dec 2020  路  2Comments  路  Source: tiangolo/fastapi

Hello. I need to dome something like this:

class Pagination:
    # some pagination dependency logic

    @staticmethod
    def get_paginated_schema(schema):
        class PaginatedSchema(BaseModel):
            count: int
            next: Optional[AnyHttpUrl]
            previous: Optional[AnyHttpUrl]
            results: schema

        return PaginatedSchema


PaginatedOperation = Pagination.get_paginated_schema(List[Operation])

But if there're two or mode schemas I get an error:

File ".../lib/python3.8/site-packages/fastapi/utils.py", line 29, in get_model_definitions model_name = model_name_map[model] KeyError: <class 'common.pagination.Pagination.get_paginated_schema.<locals>.PaginatedSchema'>
Is there a way to work around it?

question

Most helpful comment

Try using generic models instead? https://pydantic-docs.helpmanual.io/usage/models/#generic-models

All 2 comments

Try using generic models instead? https://pydantic-docs.helpmanual.io/usage/models/#generic-models

@Mause Thank you, that's exactly what I was looking for.

Code can be like this:

BaseSchemaT = TypeVar('BaseSchemaT')

class Pagination:

    class Paginated(GenericModel, Generic[BaseSchemaT]):

        count: int
        next: Optional[AnyHttpUrl]
        previous: Optional[AnyHttpUrl]
        results: List[BaseSchemaT]

    # rest of Dependency code

and a view is

@router.get(
    "/{event_id}/operations",
    response_model=Pagination.Paginated[Operation],
)
Was this page helpful?
0 / 5 - 0 ratings