How to Apply Custom Function to Return DTO Fields #3422
Unanswered
colinbrust
asked this question in
Q&A
Replies: 1 comment 2 replies
-
There's no way for DTOs to do this, as yet. You can do it without DTOs, if you have an appetite for using a custom float type for the coordinates, e.g.,: from __future__ import annotations
import msgspec
from litestar import Litestar, post
class RoundedFloat(float): ...
class Location(msgspec.Struct):
name: str
latitude: RoundedFloat
longitude: RoundedFloat
@post("/")
async def index(data: Location) -> Location:
return data
app = Litestar(
route_handlers=[index],
type_decoders=[(lambda x: issubclass(x, RoundedFloat), lambda typ, val: typ(val))],
type_encoders={RoundedFloat: lambda val: round(val, 2)},
debug=True,
) If this was to be something we support with DTOs, there is two points when the DTOs have their hands on the data:
At either of those points, we'd be able to apply a transformer function to the data for each field. |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I have a model for some location data that looks like this:
In my
return_dto
, I would like to round the latitude and longitude values. Is there a way to apply a function to the return values in yourDTOConfig
? Something along the lines of:I know that I could include a
latitude_rounded
andlongitude_rounded
field and thenexclude
the original lat/lon fields, but was just wondering if something like this is possible.Thanks!
Beta Was this translation helpful? Give feedback.
All reactions