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?
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],
)
Most helpful comment
Try using generic models instead? https://pydantic-docs.helpmanual.io/usage/models/#generic-models