Swagger Documentation Issue: Incorrect Field Definition for SerializerMethodField in Django REST Framework

Problem Description

I'm encountering an issue with generating Swagger documentation for a Django REST Framework project. Specifically, I'm using a SerializerMethodField named info in my serializer. However, in the generated Swagger documentation, it's incorrectly defined as a string, whereas info is derived from a related model and is not a string.

Example

In the Swagger documentation, info is incorrectly represented as a string:

{
  "count": 0,
  "next": "http://example.com",
  "previous": "http://example.com",
  "results": [
    {
...
      "info": "string",
...
    }
  ]
}

Relevant Serializer Code

Here's a snippet of the serializer where the issue arises:

class ProductSerializer(serializers.ModelSerializer):
...
    @staticmethod
    def get_info(obj):
        info = ProductInfo.objects.filter(product=obj.id)
        return ProductInfoSerializer(info, many=True).data
...

I tried using swagger_serializer_method, but it doesn't seem to have any effect. Here's what I attempted:

from drf_yasg.utils import swagger_serializer_method

class ProductSerializer(serializers.ModelSerializer):
...
    @staticmethod
    @swagger_serializer_method(serializer_or_field=ProductInfoSerializer().fields)
    def get_info(obj):
        info = ProductInfo.objects.filter(product=obj.id)
        return ProductInfoSerializer(info, many=True).data
...

However, this didn't resolve the issue. The problem applies to several fields, not just info.

I'm seeking guidance on how to correctly represent info and other similar fields in the Swagger documentation. Any help or suggestions would be greatly appreciated.

Back to Top