Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

288
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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!!

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!