Unexpected @field_validator behaviour
- Dominant language
- Python
- Stars
- 1.2k
- Forks
- 97
- PR merge metrics
- No merged PRs in 30d
Description
# Bug
If you create a mandatory attribute for a custom class that derives from `Model` and create a instance of this class without providing the mandatory field, you do not get a `Field required` validation error and the custom validators are run (which would is the default behaviour for the `BaseModel` classes).
### Current Behavior
```
import datetime
from typing import Optional
from odmantic import Field, Model
from pydantic import field_validator
class MyClass(Model):
date_of_birth: datetime.datetime
birth_year: Optional[int] = Field(None)
@field_validator("birth_year", mode="before")
def validate_birth_year(cls, v: int, values) -> int:
"""Validates the birth year."""
if v is None:
date_of_birth: datetime = values.data.get("date_of_birth")
v = date_of_birth.year
return v
```
running this returns
```
v = date_of_birth.year
^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'year'
```
### Expected behavior
Expected would be the output that pydantic generates you if you derive directly from `BaseModel` without running the custom validators at all:
```
pydantic_core._pydantic_core.ValidationError: 1 validation error for MyClass
date_of_birth
Field required [type=missing, input_value={}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.6/v/missing
```
### Environment
- ODMantic version: 1.0.1
- Pydantic infos (output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())`):
```
pydantic version: 2.6.4
pydantic-core version: 2.16.3
pydantic-core build: profile=release pgo=true
install path: /Users/lxr1046/Library/Caches/pypoetry/virtualenvs/clinical-etl-service-lM9J4W3w-py3.11/lib/python3.11/site-packages/pydantic
python version: 3.11.8 (main, Feb 6 2024, 21:21:21) [Clang 15.0.0 (clang-1500.1.0.2.5)]
platform: macOS-14.4-arm64-arm-64bit
related packages: fastapi-0.110.0 mypy-1.9.0 typing_extensions-4.10.0 pydantic-settings-2.2.1
commit: unknown
```
Contributor guide
Research direction
The issue provides a minimal ODMantic Model reproduction using Pydantic's field_validator and lists the affected ODMantic, Pydantic, and Python versions. Start by running that example and tracing Model validation for missing required fields; done means the missing date_of_birth produces a Field required ValidationError before the custom validator runs.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- databases
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 40/100