tezvyn:

Ensure end_date is after start_date in Pydantic

AI-drafted, machine-checkedSource: pydantic.devadvanced
Ensure end_date is after start_date in Pydantic

Tests whether you know field validators see only one value and cannot compare siblings. Use a model validator instead, which receives the full instance and can compare start_date and end_date. Red flag: a field validator referencing the other field.

WHAT THIS TESTS: This question checks whether you understand the scope and lifecycle of Pydantic validators. Specifically, it tests if you know that a field validator is limited to the single value it decorates and cannot perform cross-field checks. The interviewer wants to hear that multi-field constraints require a model-level validator that runs after individual fields have been validated.

A GOOD ANSWER COVERS: First, state clearly that a standard field validator receives only the value of the field it is attached to, so it has no access to sibling fields such as start_date when validating end_date. Second, identify the correct tool as a model validator. Third, explain that using mode after means the validator receives the fully constructed model instance with already validated and coerced types, letting you compare self.end_date and self.start_date directly. Fourth, mention that you raise a ValueError with a clear message when the constraint is violated, and Pydantic will wrap it in a ValidationError.

COMMON WRONG ANSWERS: Proposing a field validator on end_date that somehow references start_date without explaining how it would access the other field. Suggesting a before validator that manually parses raw input dictionaries instead of leveraging the typed model instance. Confusing Pydantic v1 root_validator with v2 model_validator without clarifying the new syntax and behavior. Saying you would validate in application code after model creation rather than inside the model itself.

LIKELY FOLLOW-UPS: How would you handle optional dates where either field could be None? What if the business rule required checking this condition only when the model is used in a specific context? How would you write a custom error message that associates the failure with the end_date field specifically rather than the whole model? Can a wrap validator solve this, and why is it less idiomatic than a model validator here?

ONE CONCRETE EXAMPLE: Define a Pydantic BaseModel with start_date and end_date as datetime fields. Add a method decorated with the model_validator decorator and mode set to after. Inside the method, check if self.end_date is less than or equal to self.start_date, and if so raise ValueError with the message end_date must be after start_date. Because mode is after, both dates have already been parsed from strings to datetime objects, so the comparison is type-safe and reliable.

Read the original → pydantic.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.