-
Notifications
You must be signed in to change notification settings - Fork 14
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
feature: Add Serializer field name changing by Pydantic alias / validation_alias #24
base: main
Are you sure you want to change the base?
Conversation
Codecov ReportAll modified and coverable lines are covered by tests ✅
Additional details and impacted files@@ Coverage Diff @@
## main #24 +/- ##
==========================================
+ Coverage 98.83% 98.93% +0.10%
==========================================
Files 5 5
Lines 171 188 +17
==========================================
+ Hits 169 186 +17
Misses 2 2 ☔ View full report in Codecov by Sentry. |
Thank you for the contribution. There are three alias features in pydantic:
|
Thanks for the quick reply! I made some changes based on your comment, and added Serializer The use cases are described in the new tests. The only thing that might not look good is changing the arguments in |
I wanted to confirm my understanding of I think any class Foo(BaseModel):
bar: Annotated[
str,
Field(alias="spam"), # sets 'source'
DrfFieldNameOverride("baz"), # sets attribute name
] resulting in class FooSerializer(serializers.Serializer):
baz = serializers.CharField(source="spam") With that in mind, I suggest moving
|
Hello!
In my case I use
.drf_serializer()
to create auto generation of documentation for API query parameters by drf_spectacular.There are scenarios where QuerySet filters are passed as a query parameter that can look bad, such as
main_model_field__related_field__icontains
. When further interacting with the object I want to use this field name, but pass a prettier version to the API, for examplefield
.In Pydantic I use
validation_alias
for this purpose, which allows me to passfield
duringBaseModel
initialization, but instance will containmain_model_field__related_field__icontains
.Example:
Unfortunately, this version of
drf_pydantic
does not provide tools for parsingalias / validation_alias / serialization_alias
, so in this Pull Request I propose my solution, which createsSerializers
for inputs that change field names depending on the presence ofalias / validation_alias
Also, this solution can be useful when convert camelCase to snake_case.
Example:
(Serializer
source
doesn`t work at this situation)