Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove redundant instance variables "context" and "instance" #11

Merged
merged 1 commit into from
Jun 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 3 additions & 9 deletions djantic/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
34 changes: 34 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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):
Expand Down
Loading