Skip to content
This repository was archived by the owner on Apr 2, 2025. It is now read-only.

Commit 671d66a

Browse files
committed
remove nulls from serialized links
1 parent 6919ab5 commit 671d66a

File tree

2 files changed

+13
-8
lines changed

2 files changed

+13
-8
lines changed

src/stapi_fastapi/models/product.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,6 @@ def with_links(self: Self, links: list[Link] | None = None) -> Self:
7676

7777

7878
class ProductsCollection(BaseModel):
79-
type: Literal["ProductCollection"] = "ProductCollection"
79+
type_: Literal["ProductCollection"] = Field("ProductCollection", alias="type")
8080
links: list[Link] = Field(default_factory=list)
8181
products: list[Product]

src/stapi_fastapi/models/shared.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
from typing import Any, Self
22

3-
from pydantic import AnyUrl, BaseModel, ConfigDict
3+
from pydantic import (
4+
AnyUrl,
5+
BaseModel,
6+
ConfigDict,
7+
SerializerFunctionWrapHandler,
8+
model_serializer,
9+
)
410

511

612
class Link(BaseModel):
@@ -19,9 +25,8 @@ class Link(BaseModel):
1925
def __init__(self, href: AnyUrl | str, **kwargs):
2026
super().__init__(href=href, **kwargs)
2127

22-
def model_dump_json(self: Self, *args, **kwargs) -> str:
23-
# TODO: this isn't working as expected and we get nulls in the output
24-
# maybe need to override python dump too
25-
# forcing the call to model_dump_json to exclude unset fields by default
26-
kwargs["exclude_unset"] = kwargs.get("exclude_unset", True)
27-
return super().model_dump_json(*args, **kwargs)
28+
# overriding the default serialization to filter None field values from
29+
# dumped json
30+
@model_serializer(mode="wrap", when_used="json")
31+
def serialize(self: Self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
32+
return {k: v for k, v in handler(self).items() if v is not None}

0 commit comments

Comments
 (0)