Skip to content
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

feat: Added conversion of Pydantic's 'description' field into DRF's '… #23

Merged
merged 5 commits into from
May 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
.vscode
.venv
.devcontainer
.idea

# Python
*.py[cod]
Expand Down
7 changes: 7 additions & 0 deletions src/drf_pydantic/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,13 @@ def _convert_field(field: pydantic.fields.FieldInfo) -> serializers.Field:
if _default_value is not pydantic_core.PydanticUndefined:
drf_field_kwargs["default"] = _default_value

# Adding description as help_text
if (
field.description is not pydantic_core.PydanticUndefined
and field.description is not None
):
drf_field_kwargs["help_text"] = field.description

# Process constraints
for item in field.metadata:
if isinstance(item, pydantic.StringConstraints):
Expand Down
7 changes: 7 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,8 @@ class Person(BaseModel):
field_5: typing.Optional[str]
field_6: typing.Optional[str] = "default"
field_7: typing.Optional[str] = None
field_8: typing.Annotated[str, pydantic.Field(description="8th field")]
field_9: str = pydantic.Field(default="default", description="9th field")

serializer = Person.drf_serializer()

Expand Down Expand Up @@ -600,6 +602,11 @@ class Person(BaseModel):
assert serializer.fields["field_6"].allow_null is True
assert serializer.fields["field_7"].allow_null is True

assert serializer.fields["field_6"].help_text is None
assert serializer.fields["field_7"].help_text is None
assert serializer.fields["field_8"].help_text == "8th field"
assert serializer.fields["field_9"].help_text == "9th field"


class TestManualFields:
def test_same_type(self):
Expand Down
Loading