Repository navigation
How do I change/fix the order of fetched field? #1719
Unanswered
llama-for3ver
asked this question in
Q&A
Replies: 1 comment
|
Control the output through an explicit Pydantic response model. Pydantic preserves declared field order during serialization; returning ORM objects directly does not define that presentation order. For Pydantic 2: from pydantic import BaseModel, ConfigDict
class VehicleResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
identifier: str
country: str
vehicle_type: str
vehicle_sub_types: list[str] | None = None
@router.get("/", response_model=list[VehicleResponse])
async def get_vehicles():
return await Vehicle.all().limit(5)Declare your remaining response fields in the order you want. This shortened example returns only the four declared fields, because FastAPI filters output through the response model. Keep
References: Pydantic field ordering, FastAPI response models. |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I have a simple setup w/ FastAPI:
The problem is that I want the response fields to be in a specific order, as defined by the database and model, it seems to be in a random order. Here's what it is supposed to be:
(this is as from asyncpg)
Is it possible to do this?
All reactions