Search code examples
djangodjango-rest-frameworkdrf-spectacular

drf_spectacular schema annotation for optional serializer return type


I have a Django Rest Framework ModelSerializer with the following SerializerMethodField:

def get_segment(self, obj):
    segment = models.Segment.objects.filter(obj=obj)
    if segment.exists():
        return SegmentSerializer(segment.first()).data

I'm trying to use drf_spectacular's extend_schema_field to annotate the return type. @extend_schema_field(SegmentSerializer), is close, but my function can also return None, so I want to do something like @extend_schema_field(SegmentSerializer | None), which doesn't work. Is there a way to use a serializer type in extend_schema_field while marking it as nullable?


Solution

  • I solved this by using the allow_null parameter, which allows a serializer to accept None, serializing to null:

    @extend_schema_field(SegmentSerializer(allow_null=True))