Skip to content

Commit

Permalink
handle unannotated composite fields
Browse files Browse the repository at this point in the history
  • Loading branch information
georgebv committed Aug 28, 2024
1 parent b5b8e66 commit 7314910
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 10 deletions.
4 changes: 4 additions & 0 deletions src/drf_pydantic/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@
datetime.date: serializers.DateField,
datetime.time: serializers.TimeField,
datetime.timedelta: serializers.DurationField,
# Scalar collections
list: serializers.ListField,
tuple: serializers.ListField,
dict: serializers.DictField,
}


Expand Down
44 changes: 34 additions & 10 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,18 +342,29 @@ class Person(BaseModel):
assert isinstance(serializer.fields["gender"], serializers.ChoiceField)
assert serializer.fields["gender"].choices == {0: 0, 1: 1}

def test_literal(self):
class Employee(BaseModel):
department: typing.Literal["engineering", "sales", "marketing"]
def test_scalar_list(self):
class Person(BaseModel):
data: list

serializer = Employee.drf_serializer()
serializer = Person.drf_serializer()

assert isinstance(serializer.fields["department"], serializers.ChoiceField)
assert serializer.fields["department"].choices == {
"engineering": "engineering",
"sales": "sales",
"marketing": "marketing",
}
assert isinstance(serializer.fields["data"], serializers.ListField)

def test_scalar_tuple(self):
class Person(BaseModel):
data: tuple

serializer = Person.drf_serializer()

assert isinstance(serializer.fields["data"], serializers.ListField)

def test_scalar_dict(self):
class Person(BaseModel):
data: dict

serializer = Person.drf_serializer()

assert isinstance(serializer.fields["data"], serializers.DictField)

def test_pydantic_json_value(self):
class Person(BaseModel):
Expand Down Expand Up @@ -501,6 +512,19 @@ class Person(BaseModel):
assert "Error when converting model: Person" in str(exc_info.value)
assert "is not a supported dict type" in str(exc_info.value)

def test_literal(self):
class Employee(BaseModel):
department: typing.Literal["engineering", "sales", "marketing"]

serializer = Employee.drf_serializer()

assert isinstance(serializer.fields["department"], serializers.ChoiceField)
assert serializer.fields["department"].choices == {
"engineering": "engineering",
"sales": "sales",
"marketing": "marketing",
}

def test_unsupported_type_error(self):
with pytest.raises(ModelConversionError) as exc_info:
T = typing.TypeVar("T")
Expand Down

0 comments on commit 7314910

Please sign in to comment.