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?
I had raised this issue in FastAPI and Pydantic discussions. And found the answer here by a community member: https://github.com/tiangolo/fastapi/discussions/4563
The solution is to rename the def validate func to anything else like def validate_all_fields
And the reason for this is validate is base method for BaseModel in Pydantic!!