Describe the bug
I've got a SerializerMethodField that returns a moderately complex object of the form:
[
{
"component": "component 1",
"counts": {
"cat1": 1,
"cat2": 2,
...
}
},
{
"component": "component 2",
"counts": {
"cat1": 1,
"cat2": 2,
...
}
},
...
]
So, I did this:
class RatingSummary(TypedDict):
component: str
counts: Dict[str, int]
class ContractorSerializer(serializers.HyperlinkedModelSerializer):
rating_summary = serializers.SerializerMethodField()
def get_rating_summary(self, contractor: Contractor) -> List[RatingSummary]:
...
But, it doesn't work; I get this error message:
Warning #0: could not resolve type for "<class 'xxx.rest.serializers.RatingSummary'>". defaulting to "string"
To Reproduce
It looks like the specific part that makes it fail is having the return type be List[ < any complex type >] -- that is, List[int] or List[string] works correctly, but List[Dict[str, str]], or any non-primitive type, fails.
Expected behavior
I'd love for this to work!
Workaround
There is an OK workaround, which is to define a serializer rather than the type hint, and annotate that on with @extend_schema_field - e.g.:
class RatingSummarySerializer(serializers.Serializer):
component = serializers.CharField()
counts = serializers.DictField(child=serializers.IntegerField())
class ContractorSerializer(serializers.HyperlinkedModelSerializer):
@extend_schema_field(RatingSummarySerializer)
def get_rating_summary(self, contractor: Contractor) -> List[RatingSummary]:
...
This isn't perfect because RatingSummarySerializer isn't actually a serializer -- it's really just there for schema generation -- so that makes the code slightly confusing. But it's an acceptable workaround, IMO.
Describe the bug
I've got a
SerializerMethodFieldthat returns a moderately complex object of the form:[ { "component": "component 1", "counts": { "cat1": 1, "cat2": 2, ... } }, { "component": "component 2", "counts": { "cat1": 1, "cat2": 2, ... } }, ... ]So, I did this:
But, it doesn't work; I get this error message:
Warning #0: could not resolve type for "<class 'xxx.rest.serializers.RatingSummary'>". defaulting to "string"To Reproduce
It looks like the specific part that makes it fail is having the return type be
List[ < any complex type >]-- that is,List[int]orList[string]works correctly, butList[Dict[str, str]], or any non-primitive type, fails.Expected behavior
I'd love for this to work!
Workaround
There is an OK workaround, which is to define a serializer rather than the type hint, and annotate that on with
@extend_schema_field- e.g.:This isn't perfect because
RatingSummarySerializerisn't actually a serializer -- it's really just there for schema generation -- so that makes the code slightly confusing. But it's an acceptable workaround, IMO.