From 7cc6214ae432e6ae341a1899929e6f1d466ed7a0 Mon Sep 17 00:00:00 2001 From: Jonathan Sundqvist Date: Tue, 11 Jun 2024 22:14:46 +0200 Subject: [PATCH] Remove redundant instance variables "context" and "instance" (#11) The following two instance variables "context" and "instance" are no longer set in the "from_django" function as these have no use. The "dump" parameter is also removed, as it was added by mistake in the refactor to accomodate pydantic 2. fixes #10 --- djantic/main.py | 12 +++--------- tests/test_fields.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 9 deletions(-) diff --git a/djantic/main.py b/djantic/main.py index 5fe91d3..d42bd2c 100644 --- a/djantic/main.py +++ b/djantic/main.py @@ -251,24 +251,18 @@ def from_orm(cls, *args, **kwargs): return cls.from_django(*args, **kwargs) @classmethod - def from_django(cls, objs, many=False, context={}, dump=False): - # TODO is context really passed into model_validate, test this - cls.context = context + def from_django(cls, objs, many=False, context={}): if many: result_objs = [] for obj in objs: - cls.instance = obj obj = ProxyGetterNestedObj(obj, cls) instance = cls(**obj.dict()) - result_objs.append(cls.model_validate(instance)) + result_objs.append(cls.model_validate(instance, context=context)) return result_objs - cls.instance = objs - # NOTE question mark around the code above. - obj = ProxyGetterNestedObj(objs, cls) instance = cls(**obj.dict()) - return cls.model_validate(instance) + return cls.model_validate(instance, context=context) _is_base_model_class_defined = True diff --git a/tests/test_fields.py b/tests/test_fields.py index cf93c55..8313909 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -2,6 +2,12 @@ from pydantic import ConfigDict from testapp.models import Configuration, Listing, Preference, Record, Searchable, User +from pydantic import ( + ValidationInfo, + field_validator, + ValidationError, +) + from djantic import ModelSchema @@ -33,6 +39,34 @@ 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, + revalidate_instances='always' + ) + + @field_validator('first_name', mode="before", check_fields=False) + @classmethod + def validate_first_name(cls, v: str, info: ValidationInfo): + if not info.context: + return v + + check_title = info.context.get('check_title') + if check_title and not 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") + with pytest.raises(ValidationError): + UserSchema.from_django(user, context=get_context()) + + @pytest.mark.django_db def test_unhandled_field_type(): class SearchableSchema(ModelSchema):