首页 > 解决方案 > Django REST Framework:指定 SerializerMethodField 的数据类型

问题描述

似乎 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 模式中,此字段显示为字符串字段。有没有办法为 SerializerMethodField 设置正确的数据类型?

标签: pythondjangodjango-rest-framework

解决方案


这是一个有点笨拙的解决方案,但这对我有用:

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 自变量类型函数可以用作创建两个类的子类的简写。

如果有人对此有更好的解决方案或意见,请告诉我。


推荐阅读