-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Description
Question | Feature Request | Bug
For bugs/questions:
- OS: Ubuntu 18.04
- Python version: 3.7.3 (default, Mar 26 2019, 00:55:50) [GCC 7.3.0]
- Pydantic version: 0.23
Note: I asked this question on StackOverflow.
Now, BaseModel objects can only be constructed from dict. But it's very desirable to construct BaseModel object from another BaseModel objects.
This is my case:
I have a webhook which is used for whole protocol. All different data types are passed as json body.
@app.route("/", methods=['POST'])
async def telegram_webhook(request):
update = Update.parse_obj(request.json)
/* do something with update */I use Update model for validation (which is used are base validation):
class Update(BaseModel):
update_id: int
message: Optional[Message]
...
class Message(BaseModel):
message_id: int
text: Optional[str]But later, I want to apply additional validation to Message (so to check that it is TextMessage and to convert to it):
class TextMessage(Message):
text: str # Now is required
@validator('text')
def check_text_length(cls, value):
length = len(value)
if length > 4096:
raise ValueError(f'text length {length} is too large')
return valueSo I get Message object in function and get expection:
def process_text_message(message):
text_message = TextMessage.parse_obj(message)
How to solve this?
It would be great, if I could get entry dict, convert it to BaseModel object and process all validation / conversions / etc through BaseModel, without conversions to dict. And at the end, as last step, to convert it back to dict (for example to insert into MongoDB)