The ExpenseUpdate Model
Exit

The ExpenseUpdate Model

Create a Pydantic model where every field is optional for partial updates

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Why a separate model?

The Expense model requires description, amount, and category. That is correct for creating an expense — every new record needs those fields. But for updates, requiring all fields defeats the purpose of PATCH. A client fixing only the amount should not need to resend the description and category.

You need a second model where every field is optional. If the client sends a field, Pydantic validates it. If the client omits a field, Pydantic marks it as unset.

Making fields optional with defaults

Setting default=None inside Field() makes a field optional while keeping its validation constraint active:

amount: Optional[float] = Field(default=None, gt=0)

  • If the client sends "amount": 15.0, Pydantic checks that 15.0 is greater than 0. Valid.
  • If the client sends "amount": -5, Pydantic rejects it. The gt=0 rule still applies.
  • If the client omits amount entirely, the value is None and Pydantic skips validation.

This pattern gives you optional fields with the same safety rules as the original model.

Instructions

Create the ExpenseUpdate model below the Expense class.

  1. Create a class named ExpenseUpdate that inherits from BaseModel.
  2. Add description as Optional[str] with Field(default=None, min_length=1).
  3. Add amount as Optional[float] with Field(default=None, gt=0).
  4. Add category as Optional[Literal["food", "transport", "entertainment", "utilities", "other"]] with a default of None.