Skip to content

Commit

Permalink
Remove redundant instance variables "context" and "instance"
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jonathan-s committed Jun 11, 2024
1 parent 65e717b commit 512a793
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 9 deletions.
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

0 comments on commit 512a793

Please sign in to comment.