How to change name of items field of the Page model? #778
Answered
by
lelecanfora
lelecanfora
asked this question in
Q&A
-
Is there an elegant way to change the name of the field "items" of the Page model that is outputted by fast api pagination? For example instead of this output: {
"items": [
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
}
],
"total": 0,
"page": 0,
"size": 0,
"pages": 0
} I would like to have this output {
"objects": [
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
}
],
"total": 0,
"page": 0,
"size": 0,
"pages": 0
} In Pydantic unfortunately you have to redeclare the Field in full if you want to override on a child class. |
Beta Was this translation helpful? Give feedback.
Answered by
lelecanfora
Aug 23, 2023
Replies: 1 comment 1 reply
-
Hi @lelecanfora, Sorry for a long response. I hope answers bellow will help you: For from typing import Generic, TypeVar
from fastapi import FastAPI
from pydantic import Field
from fastapi_pagination import Page, add_pagination, paginate
T = TypeVar("T")
class ObjectsPage(Page[T], Generic[T]):
items: list[T] = Field(..., alias="objects")
class Config:
allow_population_by_field_name = True
app = FastAPI()
@app.get("/items")
def get_items() -> ObjectsPage[int]:
return paginate([*range(1_000)])
add_pagination(app) For from typing import Generic, TypeVar
from fastapi import FastAPI
from pydantic import Field
from fastapi_pagination import Page, add_pagination, paginate
T = TypeVar("T")
class ObjectsPage(Page[T], Generic[T]):
items: list[T] = Field(..., alias="objects")
model_config = {
"populate_by_name": True,
}
app = FastAPI()
@app.get("/items")
def get_items() -> ObjectsPage[int]:
return paginate([*range(1_000)])
add_pagination(app) |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes, that seems easy enough, I ended up creating a class generator and it works as intended: