Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
680 views
in Technique[技术] by (71.8m points)

python - How to modify pydantic field when another one is changed?

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...