Pydantic Model : result converting without alias
dinuth-perera opened this issue · 2 comments
as above mentioned line , by_alias=True
using only when orm_mode = True
. This behavior some time issue with response data. ( Look below my one of practical case - 1)
practical case - 1
class Customer(BaseModel):
abc_user_id: int = Field(alias="id")
class Config:
orm_mode = True
getter_dict = utils.GenericOdooGetter
//Expecting output
{"id":0}
//Output ( with this issue)
{"abc_user_id":0}
Suggestion
(
def to_response(self, service, result):
json_dict = result.dict(by_alias=True)
....
Also no need validation here . Because if we need validation, we can do it with Model
- Config
.
Open to discuss.
Thanks.
Thank you for opening the discussion on this topic.
The problem here is that the same field is used for 2 different purposes:
- The serialization of our model instance into a json document.
- The initialization of our model instance from an other object instance (the orm mode)
In the first case, if the alias is used we expect that the when the instance will be serialized into json, the alias will be used as key.
In the second case, we expect that the field in our model instance will be initialized from a field named as specified by the alias into the original object instance when using from_orm
How can we deal with the case where we expect that the field is initialized from the field 'id' from orm and should be serialized as abc_user_id
or id
?
Also no need validation here . Because if we need validation, we can do it with Model - Config.
The goal is to be sure that only valid messages are returned by a call to the api. The validation by config will not work for missing fields for example. It only allows the validation at field assignment but if a required field is not assigned, it will not throw an exception.
There hasn't been any activity on this issue in the past 6 months, so it has been marked as stale and it will be closed automatically if no further activity occurs in the next 30 days.
If you want this issue to never become stale, please ask a PSC member to apply the "no stale" label.