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

Fix dict when validate assignment true #1024

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
2 changes: 1 addition & 1 deletion ninja/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions tests/test_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -194,3 +195,23 @@ class Somechema(Schema):

dg = DjangoGetter({"i": 1}, Somechema)
assert repr(dg) == "<DjangoGetter: {'i': 1}>"


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