Skip to content

Commit

Permalink
fix: fix some errors after rename
Browse files Browse the repository at this point in the history
  • Loading branch information
jhassine committed Nov 19, 2024
1 parent ff5c6e3 commit c95ee5a
Show file tree
Hide file tree
Showing 13 changed files with 433 additions and 464 deletions.
4 changes: 2 additions & 2 deletions django2pydantic/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Super schema packages."""

from django2pydantic.schema import django2pydantic
from django2pydantic.schema import Schema
from django2pydantic.types import Infer, InferExcept, MetaFields, ModelFields

__all__ = ["Infer", "InferExcept", "ModelFields", "MetaFields", "django2pydantic"]
__all__ = ["Infer", "InferExcept", "ModelFields", "MetaFields", "Schema"]
__version__ = "0.0.1"
6 changes: 3 additions & 3 deletions django2pydantic/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,16 +261,16 @@ def __new__( # pylint: disable=W0222,C0204
namespace: Namespace,
**kwargs: Kwargs,
) -> type[BaseModel]:
"""Create a new django2pydantic class."""
if name == "django2pydantic":
"""Create a new Schema class."""
if name == "Schema": # TODO: detect more reliably if this is the base class
return super().__new__(cls, name, bases, namespace, **kwargs)

if "Meta" not in namespace:
msg = f"Meta class is required for {name}"
raise ValueError(msg)

if getattr(namespace["Meta"], "model", None) is None:
msg = f"model class is required in Meta class for {name}"
msg = f"'model' attribute is required in Meta class for {name}"
raise ValueError(msg)

model_class = namespace["Meta"].model
Expand Down
15 changes: 2 additions & 13 deletions django2pydantic/getter.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Getter for Pydantic related Django models."""

from typing import Any, reveal_type
from typing import Any

from django.db.models import Manager, QuerySet
from django.db.models.fields.files import FieldFile
Expand All @@ -21,11 +21,9 @@ def _convert_result(
) -> Result:
"""Convert the result to a serializable format."""
if isinstance(result, Manager):
print("MANAGER", result)
return list(result.all())

if isinstance(result, getattr(QuerySet, "__origin__", QuerySet)):
print("QUERYSET")
return list(result)

if callable(result):
Expand Down Expand Up @@ -53,6 +51,7 @@ def _get_prefetched_values(self, key: str) -> Result:
"some_key__id": 1,
"some_key__name": "Some Name",
}
"""
values = {}
for k, v in self._obj.items():
Expand All @@ -65,12 +64,6 @@ def __init__(self, obj: Any, schema_cls: Any, context: Any = None) -> None:
self._obj = obj
self._schema_cls = schema_cls
self._context = context
print("OBJ", self._obj)
reveal_type(self._obj)
print(type(self._obj))
print("SCHEMA", self._schema_cls)
reveal_type(self._schema_cls)
print(type(self._schema_cls))

def __getattr__(self, key: str) -> Result:
"""Get the attribute from the object."""
Expand All @@ -85,16 +78,12 @@ def __getattr__(self, key: str) -> Result:
if isinstance(self._obj, dict):
if key not in self._obj:
return self._get_prefetched_values(key)
print(f"Key {key} not found in {self._obj}")
raise AttributeError(key)
value = self._obj[key]
else:
try:
value = getattr(self._obj, key)
except AttributeError as e:
print(f"AttributeError: {e}")
raise AttributeError(key) from e

print(f"{key} -> {value}")

return self._convert_result(value)
1 change: 0 additions & 1 deletion django2pydantic/mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,5 @@ def _run_root_validator(
info: ValidationInfo,
) -> SVar:
"""Run the root validator."""
print("-----------Root Validator-----------")
values = DjangoGetter(values, cls, info.context)
return handler(values)
27 changes: 4 additions & 23 deletions django2pydantic/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,14 @@
from django2pydantic.getter import DjangoGetter
from django2pydantic.types import ModelFields

S = TypeVar("S", bound=BaseModel)
SType = TypeVar("SType", bound=BaseModel)

DictStrAny = dict[str, Any]


class django2pydantic(BaseModel, metaclass=SuperSchemaResolver):
class Schema(BaseModel, metaclass=SuperSchemaResolver):
"""django2pydantic class."""

# model_config = ConfigDict(from_attributes=True)

class Config:
"""Pydantic configuration."""

Expand All @@ -38,29 +36,12 @@ class Meta:
def _run_root_validator(
cls,
values: Any,
handler: ModelWrapValidatorHandler[S],
handler: ModelWrapValidatorHandler[SType],
info: ValidationInfo,
) -> S:
print("z--x-------Root Validator-----------")
print("Values", values)
print("Handler", handler)
print("Info", info)
print("end rv")
) -> SType:
forbids_extra = cls.model_config.get("extra") == "forbid"
should_validate_assignment = cls.model_config.get("validate_assignment", False)
if forbids_extra or should_validate_assignment:
handler(values)
values = DjangoGetter(obj=values, schema_cls=cls, context=info.context)
return handler(values)

"""
@model_validator(mode="before")
@classmethod
def _run_root_validator(
cls,
values: Any,
info: ValidationInfo,
) -> DjangoGetter:
print("-----------Root Validator-----------")
return DjangoGetter(values, cls, info.context)
"""
Loading

0 comments on commit c95ee5a

Please sign in to comment.