Expose derived data with computed_field
Derived data should have one source of truth. Storing a subtotal alongside its inputs allows the values to disagree. A computed field exposes a property in model serialization while calculating its value from validated inputs.
The property is not an independently validated input field. Use it for deterministic derived information, and remember that repeatedly accessing an ordinary property recomputes it. Keep expensive or effectful work out of serialization. If a value depends on external state, computing it explicitly in a service is usually a clearer boundary.
from pydantic import BaseModel
from pydantic import computed_field
class Square(BaseModel):
side: int
@computed_field
@property
def area(self) -> int:
return self.side * self.side
print(Square(side=3).model_dump())Your task
Implement invoice_data(raw) with Invoice(price:float>=0, quantity:int>=0) and computed total:float. Return a dump containing price, quantity and total. Ignore any supplied total and calculate it from inputs.
The explanation opens here once every check passes.