Python Django REST框架:指定SerializerMethodField的数据类型
SerializerMethodField似乎假定字段的数据类型是字符串,即使它是int。例如,我有以下字段:Python Django REST框架:指定SerializerMethodField的数据类型,python,django,django-rest-framework,Python,Django,Django Rest Framework,SerializerMethodField似乎假定字段的数据类型是字符串,即使它是int。例如,我有以下字段: num_sections = serializers.SerializerMethodField(help_text="The number of sections for this course") def get_num_sections(self, obj) -> int: return obj.sections.count() 但是,在自动生成的OpenAPI
num_sections = serializers.SerializerMethodField(help_text="The number of sections for this course")
def get_num_sections(self, obj) -> int:
return obj.sections.count()
但是,在自动生成的OpenAPI模式中,此字段显示为字符串字段。有没有办法为SerializerMethodField设置正确的数据类型?这是一个有点繁重的解决方案,但这对我来说很有效:
num_sections = type('SerializerMethodField', (serializers.SerializerMethodField, serializers.IntegerField), dict())(
help_text="The number of sections for this course")
def get_num_sections(self, obj) -> int:
return obj.sections.count()
3参数类型函数可用作两个类的子类的缩写
如果有人对此有更好的解决方案或意见,请告诉我。您可以使用此片段:
from drf_spectacular.utils import extend_schema_field
num_sections = serializers.SerializerMethodField(help_text="The number of sections for this course")
@extend_schema_field(serializers.IntegerField)
def get_num_sections(self, obj) -> int:
return obj.sections.count()