Skip to main content

How to Check Two Fields Together in pydantic with model_validator

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

Some rules involve two fields at once: a check-out date must come after the check-in date, and a maximum must be bigger than a minimum. Each field on its own looks fine, so field checks can't catch it. pydantic's @model_validator(mode="after") runs once all fields are valid and can compare them. This guide does it with pydantic 2.14.4 on Python 3.15.2.

Syntax​

Syntax
from typing import Self

from pydantic import BaseModel, model_validator


class <Model>(BaseModel):
<field>: <type>
<field>: <type>

@model_validator(mode="after")
def <check_name>(self) -> Self:
if <rule is broken>:
raise ValueError("<message>")
return self
PartWhat it means
@model_validator(mode="after")Runs the method after pydantic has checked every field
selfThe model, with its fields already converted, such as text into dates
raise ValueError("<message>")Fails validation; pydantic turns it into a ValidationError with your message
return selfGives the model back. An after validator has to return it

pydantic's validators guide says after validators "run after the whole model has been validated. As such, they are defined as instance methods and can be seen as post-initialization hooks. Important note: the validated instance should be returned."

The Example​

A Booking has a check_in and a check_out date. The script books two nights correctly, then swaps the dates.

Prerequisites​

  • pydantic in your project, for example with uv add pydantic. This guide uses pydantic 2.14.4 on Python 3.15.2.

Step 1: Write the Script​

booking.py
from 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_out_after_check_in(self) -> Self:
if self.check_out <= self.check_in:
raise ValueError("check_out must be after check_in")
return self


print(Booking(check_in="2026-12-01", check_out="2026-12-03"))

try:
Booking(check_in="2026-12-03", check_out="2026-12-01")
except ValidationError as error:
print(error)

The booking.py script in a macOS-style code window: a Booking model with check_in and check_out dates, a model_validator in after mode that raises ValueError when check_out is not after check_in, and two bookings.

Step 2: Run It​

Terminal
uv run python booking.py
Output
check_in=datetime.date(2026, 12, 1) check_out=datetime.date(2026, 12, 3)
1 validation error for Booking
Value error, check_out must be after check_in [type=value_error, input_value={'check_in': '2026-12-03'...heck_out': '2026-12-01'}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.14/v/value_error

The terminal after uv run python booking.py: the valid booking with two dates, then 1 validation error for Booking with Value error, check_out must be after check_in.

The first booking passed, and the text dates became real date objects before the validator compared them. The swapped one failed with the validator's own message, after Value error,. The error has no field name above it, because the rule belongs to the whole model. The command works unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Forgetting return selfpydantic 2.14 warns, UserWarning: A custom validator is returning a value other than `self`., and goes onEnd the validator with return self
Checking the rule in mode="before"The fields are still raw input there, such as text instead of datesUse mode="after" for rules about converted values

Troubleshooting​

SymptomLikely causeFix
Value error, <your message> [type=value_error ...]Your validator raised ValueError: the rule is brokenFix the data; the message is yours
UserWarning: A custom validator is returning a value other than `self`.The validator has no return selfAdd it as the last line

FAQ​

Why does the error say Value error and not my field's name?​

Because a model validator checks the model as a whole, so pydantic lists the error under the model, not under one field.

What does mode="before" do?​

It runs before pydantic's own checks. The validators guide says before validators "run before Pydantic's internal parsing and validation (e.g. coercion of a str to an int)", so they get the raw input.

Conclusion​

@model_validator(mode="after") compared check_in and check_out once both were real dates, and refused a booking whose dates were swapped, with the message from your own ValueError. Return self at the end.

Additional Resources​