Given an already-loaded dictionary customers
:
class Customer(BaseModel):
id: str
first_name: str
last_name: str
address: Address
customers: dict[str, Customer] = [customer.id: customer for customer in load_customers()]
The Invoice
depends on the customer:
class Invoice(BaseModel):
order: list[Item]
amount: float
customer_id: str
@property
def customer(self) -> Customer:
return customers[self.customer_id]
Is it possible to resolve the customer_id
immediately on parsing the object?
class Invoice(BaseModel):
order: list[Item]
amount: float
customer: Customer
@field_validator('customer_id')
@classmethod
def parse_customer(cls, v: str, info) -> Customer:
return customers[v]