In Pydantic 2, when do you use field_validator versus model_validator, and how would you enforce a check-out-after-check-in rule?
answer
- one field versus the whole object
- after mode sees typed values
- self returned from the method
- empty loc on model errors
basics
~10 sPydantic 2's field_validator checks one field's value; model_validator sees the whole object. A check-out-after-check-in rule fits model_validator(mode='after'), which compares typed dates and reports its error with an empty loc.
solid answer
~40 s`@field_validator` is a class method bound to named fields; in its default `'after'` mode it gets the parsed value, and an error lands on that field's `loc`. `@model_validator` needs an explicit mode: `'after'` gets the validated instance as `self` and must return it, `'before'` gets raw input, `'wrap'` gets raw input plus a handler. For the booking rule I would write `@model_validator(mode='after')`, compare `self.check_out` with `self.check_in`, raise `ValueError`, and return `self`. That error has `type` `'value_error'` and an empty `loc`, so if the client needs it on `check_out`, I put the rule in a field validator on `check_out` and read `check_in` from `info.data`. These decorators replaced version 1's `@validator` and `@root_validator`.
code
python · 21 linesfrom datetime import date
from typing import Self
from pydantic import BaseModel, ValidationError, model_validator
class Booking(BaseModel):
check_in: date
check_out: date
@model_validator(mode='after')
def check_dates(self) -> Self:
if self.check_out <= self.check_in:
raise ValueError('check_out must be after check_in')
return self
try:
Booking(check_in='2026-11-05', check_out='2026-11-03')
except ValidationError as e:
print(e.errors(include_url=False))go deeper
Know the two decorators by name: field_validator checks a field, model_validator checks the whole model, and both raise ValueError to reject input.
Explain the after-mode contract: typed values in, self returned out, and why the model-level error carries an empty loc while a field validator's error names the field.
Show you have handled the client side: choose a field validator with info.data when the error must point at a field, and tolerate the earlier field having failed.
Set a team convention for where cross-field rules live, weighing readable model-level checks against error locations that a client form can actually use.
## Two levels of custom validation Pydantic 2 gives you two decorators for rules the type hints cannot express. **`@field_validator`** attaches a function to one or more named fields. **`@model_validator`** attaches a function to the model as a whole. Both are the version 2 replacements for the old `@validator` and `@root_validator` decorators, which still exist only as deprecated shims. The choice matters most for a **cross-field rule**: a rule that compares two or more fields, such as "check-out must fall after check-in" on a hotel booking. A single field validator only sees its own value by default, so the natural home for that rule is the model level. ## `field_validator`: one field at a time - Declared as a class method: `@field_validator('phone')` above `@classmethod`. - It can name several fields (`@field_validator('f1', 'f2')`) or `'*'` for every field. - Its default mode is `'after'`, so it receives the value **after** Pydantic has parsed it against the annotation: a `date`, not the string `'2026-11-03'`. - It may take a second argument, a **`ValidationInfo`**, whose `data` property holds the fields validated **before** this one, in the order the fields are defined. - An error it raises is reported with the field's own name in `loc`, for example `('check_out',)`. ## `model_validator`: the whole object `@model_validator` requires an explicit `mode`, and it accepts three: `'before'`, `'after'` and `'wrap'` (there is no `'plain'` mode at model level). | Mode | What the function receives | What it must return | |---|---|---| | `'after'` | the validated instance, as `self` (an instance method) | `self` | | `'before'` | the raw input, usually a dict but possibly any object | the data to validate | | `'wrap'` | the raw input plus a `handler` that runs normal validation | the instance | For the booking rule, **`mode='after'`** is the usual answer: every field is already a real `date`, so the comparison is plain Python on typed attributes. An after model validator should be an instance method; declaring it as a class method is deprecated and draws a warning. ## How the error is reported When a model validator raises `ValueError`, Pydantic catches it and adds one entry to the `ValidationError`: 1. `type` is `'value_error'`. 2. `msg` is your message prefixed with `Value error, `. 3. `loc` is an **empty tuple**, `()`, because the error belongs to the model rather than to any one field. 4. `input` is the whole input the model received. That empty `loc` is the cost of the model-level approach. A client that highlights form fields from `loc` has nowhere to put the message. If the error must sit on `check_out`, move the rule into a field validator on `check_out` and read the earlier field from `info.data`: ```python @field_validator('check_out') @classmethod def after_check_in(cls, value: date, info: ValidationInfo) -> date: check_in = info.data.get('check_in') if check_in is not None and value <= check_in: raise ValueError('check_out must be after check_in') return value ``` This works only because `check_in` is defined above `check_out`, and it must tolerate `check_in` being absent, because a field that failed its own validation is not in `info.data`. ## When each one runs - Field validators run as each field is validated, and errors from different fields are **collected**, so one `ValidationError` can report a bad phone number and a bad date together. - An **after** model validator runs only when every field has validated. If `check_in` fails to parse, the date-order rule never runs, and the error list shows only the parsing failure. - A **before** model validator runs first, on raw input, which suits renaming or rejecting keys before field validation; it cannot rely on types. ## Choosing in an interview - A rule about one value (normalise a phone number, reject a past date): **field validator**. - A rule across fields where a model-level message is fine: **after model validator**. - A rule across fields where the error must name a field: **field validator with `info.data`**, on the later field. - A reshape of the raw payload before anything else: **before model validator**. ## Mistakes interviewers listen for - Forgetting `return self` in an after model validator. When the model is built through its constructor, Pydantic warns that a custom validator is returning a value other than `self`. - Writing the after model validator as a class method that expects a dict of values. That was the version 1 `@root_validator` shape; in version 2 the after mode works on the instance. - Assuming the date-order rule protects data when `check_in` is invalid. It does not run then, so the client sees only the parsing error first and the ordering error on the next attempt. - Reading `info.data['check_in']` without a guard, which turns a bad `check_in` into an escaped `KeyError` instead of a clean validation error.
- In Pydantic 2, if check_in fails to parse, does the after model validator still run?No. An after model validator runs only once every field has validated, because it needs a constructed instance. The `ValidationError` reports the `check_in` parsing failure, and the date-order rule is simply not evaluated until the input is fixed and resubmitted.
- In Pydantic 2, when would you pick model_validator(mode='before') instead?When you must act on the raw payload before field validation: rejecting a forbidden key, or reshaping an old payload into the current one. The function is a class method that receives whatever was passed in, usually a dict but not always (with `from_attributes` it can be an object), so it must check the input's type before touching it.
- A field validator on check_in can see check_out by default.
- model_validator(mode='after') receives a dict of values to return.
- An after model validator runs even when a field failed.
- Model-level errors are reported under the last field's name.
- Writing @root_validator is the current way to do cross-field checks.
Assumes Pydantic 2; field_validator and model_validator replaced version 1's @validator and @root_validator, which survive only as deprecated shims.