Fastapi: Returning an alias of a Field in a response_model

Created on 12 Nov 2020  路  3Comments  路  Source: tiangolo/fastapi

Hi,
i try to return a response_model in which I change the alias to have a different name for the field (one with a dash) in the response . Settings response_model=TodoBase to this schema:

class TodoBase(BaseModel):
    due_date: Optional[datetime] = Form(None)

    class Config:
        orm_mode = True

results in:

{
  "due_date": "2020-11-11T20:15:21.858Z"
}

but if try to change it to:

class TodoBase(BaseModel):
    due_date: Optional[datetime] = Form(None, alias="due-date")

    class Config:
        orm_mode = True

it results in:
```json
{
"due_date": null
}

What's wrong? Thanks in advance.

question

All 3 comments

what is the body of your post request?
due_date or due-date?

I fixed my issue by adding allow_population_by_field_name = True to the Pydantic model config. Not entirely sure, but I think the problem was that I returned a database model and FastAPI (or Pydantic) could not find "due-date" in it.

That option was very hard to find, maybe it should be mentioned in the documentation. Also the possibility to add an alias to a Pydantic model should be mentioned. Even if it's rather a Pydantic topic, it's pretty useful and not really obvious you can use that.

@emilpaw please close the issue if it has been solved

Was this page helpful?
0 / 5 - 0 ratings