diff --git a/ninja/schema.py b/ninja/schema.py index f2f16341..f0e78582 100644 --- a/ninja/schema.py +++ b/ninja/schema.py @@ -42,7 +42,7 @@ def resolve_name(obj): class DjangoGetter: - __slots__ = ("_obj", "_schema_cls", "_context") + __slots__ = ("_obj", "_schema_cls", "_context", "__dict__") def __init__(self, obj: Any, schema_cls: Type[S], context: Any = None): self._obj = obj diff --git a/tests/test_schema.py b/tests/test_schema.py index a298297a..8f92d520 100644 --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -4,6 +4,7 @@ import pytest from django.db.models import Manager, QuerySet from django.db.models.fields.files import ImageFieldFile +from pydantic_core import ValidationError from ninja import Schema from ninja.schema import DjangoGetter, Field @@ -194,3 +195,23 @@ class Somechema(Schema): dg = DjangoGetter({"i": 1}, Somechema) assert repr(dg) == "" + + +def test_django_getter_validates_assignment(): + class ValidateAssignmentSchema(Schema): + str_var: str + + model_config = {"validate_assignment": True} + + schema_inst = ValidateAssignmentSchema(str_var="test_value") + + # Validate we can re-assign the value, this is a test for + # a bug where validate_assignment would cause an AttributeError + # for __dict__ on the target schema. + schema_inst.str_var = "reassigned_value" + try: + schema_inst.str_var = 5 + raise AssertionError() + except ValidationError: + # We expect this error, all is okay + pass