Skip to content

Commit

Permalink
feat: handle dict annotations in PydanticJSONMixin
Browse files Browse the repository at this point in the history
Generated-by: aiautocommit
  • Loading branch information
iloveitaly committed Jan 14, 2025
1 parent 363c0dd commit 085c6a9
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
5 changes: 5 additions & 0 deletions activemodel/mixins/pydantic_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ def init_on_load(self):

annotation = field_info.annotation
origin = get_origin(annotation)

# e.g. `dict` or `dict[str, str]`, we don't want to do anything with these
if origin is dict:
continue

annotation_args = get_args(annotation)
is_top_level_list = origin is list

Expand Down
4 changes: 4 additions & 0 deletions test/serialization_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@ class ExampleWithJSON(
BaseModel, PydanticJSONMixin, TypeIDMixin("json_test"), table=True
):
list_field: list[SubObject] = Field(sa_type=JSONB())
# list_with_generator: list[SubObject] = Field(sa_type=JSONB())
optional_list_field: list[SubObject] | None = Field(sa_type=JSONB(), default=None)
generic_list_field: list[dict] = Field(sa_type=JSONB())
object_field: SubObject = Field(sa_type=JSONB())
unstructured_field: dict = Field(sa_type=JSONB())
semi_structured_field: dict[str, str] = Field(sa_type=JSONB())
optional_object_field: SubObject | None = Field(sa_type=JSONB(), default=None)

normal_field: str | None = Field(default=None)
Expand All @@ -32,11 +34,13 @@ def test_json_serialization(create_and_wipe_database):
sub_object = SubObject(name="test", value=1)
example = ExampleWithJSON(
list_field=[sub_object],
# list_with_generator=(x for x in [sub_object]),
generic_list_field=[{"one": "two", "three": 3, "four": [1, 2, 3]}],
optional_list_field=[sub_object],
object_field=sub_object,
unstructured_field={"one": "two", "three": 3, "four": [1, 2, 3]},
normal_field="test",
semi_structured_field={"one": "two", "three": "three"},
optional_object_field=sub_object,
).save()

Expand Down

0 comments on commit 085c6a9

Please sign in to comment.