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

Add label from title #26

Merged
merged 4 commits into from
Jul 15, 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
4 changes: 4 additions & 0 deletions src/drf_pydantic/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,10 @@ def _convert_field(field: pydantic.fields.FieldInfo) -> serializers.Field:
):
drf_field_kwargs["help_text"] = field.description

# Adding label as title
if field.title is not pydantic_core.PydanticUndefined and field.title is not None:
drf_field_kwargs["label"] = field.title

# Process constraints
for item in field.metadata:
if isinstance(item, pydantic.StringConstraints):
Expand Down
10 changes: 10 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,8 @@ class Person(BaseModel):
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")
field_10: str = pydantic.Field(default="default", title="10th field")
field_11: typing.Annotated[str, pydantic.Field(title="11th field")]

serializer = Person.drf_serializer()

Expand Down Expand Up @@ -607,6 +609,14 @@ class Person(BaseModel):
assert serializer.fields["field_8"].help_text == "8th field"
assert serializer.fields["field_9"].help_text == "9th field"

# Field 8, Field 9 is automatically generated label
assert serializer.fields["field_8"].label == "Field 8"
assert serializer.fields["field_9"].label == "Field 9"

# This is custom defined label
assert serializer.fields["field_10"].label == "10th field"
assert serializer.fields["field_11"].label == "11th field"


class TestManualFields:
def test_same_type(self):
Expand Down