-
Hello, I have a question regarding the paginate method, specifically the additional_data field, and the logic behind sorting their contents. I have a logic that generates data for the faceted filters. Final result is something like that: {
"items": [
{
"doc_id": "some_docutment"
}
],
"total": 9997,
"page": 1,
"size": 50,
"pages": 200,
"filters": {
"year": {
"2020": 2414,
"2021": 2814,
"2022": 2661,
"2023": 2068,
"2024": 40
}
}
} The issue is that i cannot change the order of the "year" filter to make it into 2024->2020. I tried to do simple things like turning my keys into integers and sorting them after that, but apparently some logic in the paginate function still turns them into strings (i suspect pydantic library somewhere down the line is responsible for such behaviour). Is there some parameter that would allow me to sort those keys, or is there an example of how to deal with this problem with a crutch? My Page class modified in this way: from fastapi_pagination.customization import CustomizedPage, UseModelConfig
Page = CustomizedPage[
Page,
UseModelConfig(extra="allow"),
] And my pagination function looks like this (DocumentWithMeta is my pydantic class for validating Documents):
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Hi @Mithmi, Interesting case. I guess you can try to define custom Page with additional filters field: from typing import TypeVar, Generic, Optional, Dict
from pydantic import BaseModel
from fastapi_pagination import Page as BasePage
T = TypeVar("T")
F = TypeVar("F")
class Page(BasePage[T], Generic[T, F]):
filters: Optional[F] = None
class DocumentsFilter(BaseModel):
year: Dict[int, int] Usage example: from fastapi_pagination import set_page, set_params, Params, paginate
from typing import Any
with set_page(Page[Any, DocumentsFilter]), set_params(Params()):
page = paginate(
[],
additional_data={
"filters": {
"year": {
"2020": 2414,
"2021": 2814,
"2022": 2661,
"2023": 2068,
"2024": 40
}
}
}
)
print(page.model_dump_json(indent=4)) {
"items": [],
"total": 0,
"page": 1,
"size": 50,
"pages": 0,
"filters": {
"year": {
"2020": 2414,
"2021": 2814,
"2022": 2661,
"2023": 2068,
"2024": 40
}
}
} In your case you will need to create filter class and update route definition: @router.post(
"/documents",
response_model=Page[DocumentWithMeta, DocumentFilter],
)
async def get_documents(
current_user: Annotated[User, Depends(get_current_active_user)],
request: Request,
params: Params = Depends(),
) -> paginate:
documents = request.app.documents[unique_key]
filters = calc_filters_function()
return paginate(
documents,
params,
additional_data={
"filters": filters
}
) |
Beta Was this translation helpful? Give feedback.
I guess it's Swagger UI issue.
Here is simple application: