-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support serializing with the by_alias
arg set
#10
Support serializing with the by_alias
arg set
#10
Conversation
The type adapter is needed to support other things, like dataclasses and typed dicts, but we could add some logic to check if the view returns a pydantic model. |
OK, get it 👍 . Then I think the smallest possible change is what's in the PR now. If we at some point need to leverage more of the flexibility that |
|
||
|
||
class MyPydanticModel(BaseModel): | ||
a: int | ||
an_integer: int |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Changed to this name to clearly illustrate the difference between snake case and camel case.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@ljodal I added a test case as well, if you want to have a look at it.
Pydantic will, by default, serialize models with snake case. This change enables us to define custom aliases for the fields in the Pydantic model, and have the
@api
decorator serialize the model using those aliases.This behavior was possible with the previous version of Pydantic, but was removed as part of the upgrade. Probably because Pydantic does things differently internally.
The usage we want is this:
camel_case
here is a function that converts field names from snake case to camel case.@api
view that returns an instance of this class, and makes it serialize with the alias. (Or create a local decorator that wraps@api
and hardcodes this argument):The result would be a payload that looks something like this:
An alternative approach could be to move away from the
TypeAdapter
approach, and instead just callresponse.dump_model_json()
. Then the custom base class could define an override to it that and do whatever it wants with it (usingby_alias
, for example, but potentially also other things).