Pydantic - Upgrading object to another model

Viewed 1429

I have a NewUser model that is something that the end user inputs, I want to update the object to a UserInDB so that I can pass it to my db engine (DynamoDB, which expects a dict)

At the moment I'm calling .dict twice, which doesn't feel like the correct way to do it

    from pydantic import BaseModel, Field
    from datetime import datetime
    from typing import Optional
    from uuid import uuid4
    
    class NewUser(BaseModel):
        name: str
        email: str
        company_name: Optional[str]
    
    class UserInDB(NewUser):
      hash: str = Field(default_factory= lambda: uuid4())
      range = 'DATA'
      created_at: datetime = Field(default_factory= lambda: datetime.now())
    
    #...
    #Emulating what an end user would send
    user = NewUser(name='Example', company_name='example', email='example@example.com')
    
    #Is calling dict twice way to do it?
    user_in_db = UserInDB(**user.dict()).dict()
    db.create_user(user_in_db)
0 Answers
Related