Skip to content

Commit

Permalink
feat: Added conversion of Pydantic's 'description' field into DRF's '… (
Browse files Browse the repository at this point in the history
#23)

* Added conversion of Pydantic's 'description' field into DRF's 'help_text' field
  • Loading branch information
MrMika96 authored May 27, 2024
1 parent 5845119 commit 275f31c
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
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

0 comments on commit 275f31c

Please sign in to comment.