'How to make @root_validator in Pydantic return model class object rather than values?

I am currently using a root_validator in my FastAPI project using Pydantic like this:

class User(BaseModel):
    id: Optional[int]
    name: Optional[str]

    @root_validator
    def validate(cls, values):
        if not values.get("id") and not values.get("name"):
            raise ValueError("It's an error")
        return values

The issue is, when I query the request body in FastAPI, because of return values, instead of the request body being of type class User, it is just a simple python dictionary. How do I get the same object of type class User?

So initially, my request body would like this when I printed it: id=0 name='string' (which is how I want it) (and when I print the type() of it, it shows: <class 'User'>)

Here is what it looks like with return values: {"id":0, "name"="string"}

I have tried making it as just return cls, but this is what it looks like when I print it: <class 'User'> (and when I print the type() of it, it shows: <class 'pydantic.main.ModelMetaclass'>)

How to get my solution?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source