Skip to content

Commit

Permalink
potential fix for gh_647
Browse files Browse the repository at this point in the history
  • Loading branch information
s1liconcow authored and adamghill committed Feb 25, 2024
1 parent d0a44c8 commit d3b5fea
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
4 changes: 4 additions & 0 deletions django_unicorn/typer.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
parse_duration,
parse_time,
)
from pydantic import BaseModel

from django_unicorn.typing import QuerySetType

Expand Down Expand Up @@ -140,6 +141,9 @@ def cast_value(type_hint, value):
if issubclass(type_hint, Model):
continue

if issubclass(type_hint, BaseModel) or is_dataclass(type_hint):
value = type_hint(**value)
break
value = type_hint(value)
break

Expand Down
39 changes: 38 additions & 1 deletion tests/test_typer.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from dataclasses import dataclass
import datetime
from typing import Optional
from typing import List, Optional
from typing import get_type_hints as typing_get_type_hints

from pydantic import BaseModel

from django_unicorn.components import UnicornView
from django_unicorn.typer import cast_attribute_value, cast_value, get_type_hints
from example.coffee.models import Flavor
Expand Down Expand Up @@ -111,3 +114,37 @@ def test_cast_value_model_int():
actual = cast_value(type_hint, 1)

assert actual == 1


@dataclass
class TestDataClass:
name: str


class PydanticDataClass(BaseModel):
name: str


class AnotherExampleClass:
test_data: List[TestDataClass]
pydantic_data: List[PydanticDataClass]


def test_cast_value_dataclass():
example_class = AnotherExampleClass()
test_data = TestDataClass(name="foo")
example_class.test_data = [test_data]
type_hints = typing_get_type_hints(example_class)
type_hint = type_hints["test_data"]
actual = cast_value(type_hint, [{"name": "foo"}])
assert actual == [test_data]


def test_cast_value_pydantic():
example_class = AnotherExampleClass()
test_data = PydanticDataClass(name="foo")
example_class.test_data = [test_data]
type_hints = typing_get_type_hints(example_class)
type_hint = type_hints["pydantic_data"]
actual = cast_value(type_hint, [{"name": "foo"}])
assert actual == [test_data]

0 comments on commit d3b5fea

Please sign in to comment.