7

I have a pydantic class such as:

from pydantic import BaseModel
class Programmer(BaseModel):
    python_skill: float
    stackoverflow_skill: float
    total_score: float = None

Now I am calculating the total_score according to the other fields:

@validator("total_score", always=True)
def calculat_total_score(cls, v, *, values):
    return values.get("python_skill") + values.get("stackoverflow_skill")

This works fine, but now when I change one of the skills:

programmer = Programmer(python_skill=1.0, stackoverflow_skill=9.0)
print(programmer.total_score) # return 10.0
programmer.python_skill=2.0 
print(programmer.total_score) # still return 10.0

I would like the total_score to automatically update.

Any solutions? TNX!!

OrFeldman
  • 283
  • 1
  • 3
  • 6

1 Answers1

15

You can use root validator for this. It is called after every update. Like so:

from pydantic import BaseModel, validator, root_validator


class Programmer(BaseModel):
    python_skill: float
    stackoverflow_skill: float
    total_score: float = None

    class Config:
        validate_assignment = True

    @root_validator
    def calculate_total_score(cls, values):
        values["total_score"] = values.get("python_skill") + values.get("stackoverflow_skill")
        return values


programmer = Programmer(python_skill=1.0, stackoverflow_skill=9.0)
print(programmer.total_score)  # 10.0
programmer.python_skill = 2.0
print(programmer.total_score)  # 11.0

Note: There was a bug in the versions before 1.7.3, so I recommend updating

Simon
  • 5,464
  • 6
  • 49
  • 85
alex_noname
  • 26,459
  • 5
  • 69
  • 86