There is documentation for the construct classmethod that is much faster due to bypassing validation. I am now wondering if a similar thing exists for from_orm?
In the context of web applications, I think it is quite common to have an internal data model and another response data model that excludes some of the fields (FastAPI uses this pattern _a lot_). Since my internal data has already been validated, I absolutely trust it. if I now want to convert my internal to my external model (basically just omitting some fields), with from_orm can I also somehow skip validation?
I could convert the internal data to dict and then use the construct method but that seems really silly.
Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":
pydantic version: 1.4
pydantic compiled: True
install path: ~/.virtualenvs/test/lib/python3.7/site-packages/pydantic
python version: 3.7.5 (default, Oct 31 2019, 14:14:59) [GCC 7.4.0]
platform: Linux-5.3.0-7625-generic-x86_64-with-debian-buster-sid
optional deps. installed: []...
import pydantic
class Response(pydantic.BaseModel):
name: str
class Config:
orm_mode = True
class Internal(Reponse):
id: int
data = Internal(id=1, name"Sanders")
out = Response.from_orm(data) # I would like to skip validation here.
Not possible at the moment, but I'd happily review a PR to add there feature
Okay, good to know :smiley: What would be your preferred name, e.g., BaseModel.construct_from_orm?
or a kwarg to from_orm()?
@tiangolo any thoughts on what would be easier in FastAPI? Say that a route returns a certain data model and I have a response model defined. Would it be feasible to define that the response should be created using ORM mode and bypass validation?
That would be fantastic. For a query with many rows of rather, nested complicated types the validation is a bottleneck. But then I also still run into the issue of recursive construct:
https://github.com/samuelcolvin/pydantic/issues/1168
This could be feature request as well :)
@Midnighter what I would suggest you do is generate the data in any way you want and return a response directly, that skips any validation or serialization as you are doing it all in your own code.
That would let you serialize your data in any way you want and maximize performance at the expense of more custom hand-made logic. But I think I would try not to make it a default in FastAPI as it could lead to unsafe operations. You could still use the same model in the response_model just for documentation. But if you return a response directly that skips everything.
Most helpful comment
or a kwarg to
from_orm()?