diff --git a/tests/test_fields.py b/tests/test_fields.py index cf93c55..8470fb9 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -2,6 +2,11 @@ from pydantic import ConfigDict from testapp.models import Configuration, Listing, Preference, Record, Searchable, User +from pydantic import ( + ValidationInfo, + field_validator, +) + from djantic import ModelSchema @@ -33,6 +38,31 @@ class UserSchema(ModelSchema): } +@pytest.mark.django_db +def test_context_for_field(): + + def get_context(): + return {'check_title': lambda x: x.istitle()} + + class UserSchema(ModelSchema): + model_config = ConfigDict(model=User) + + @field_validator('first_name', mode="before", check_fields=False) + @classmethod + def validate_choice(cls, v: str, info: ValidationInfo): + print(info.context) + if not info.context: + return v + breakpoint() + check_title = info.context.get('check_title') + if check_title and check_title(v): + raise ValueError('First name needs to be a title') + return v + + user = User.objects.create(first_name="hello", email="a@a.com") + UserSchema.from_django(user, context=get_context()) + + @pytest.mark.django_db def test_unhandled_field_type(): class SearchableSchema(ModelSchema):