python - 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 设置正确的数据类型?
解决方案
这是一个有点笨拙的解决方案,但这对我有用:
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 自变量类型函数可以用作创建两个类的子类的简写。
如果有人对此有更好的解决方案或意见,请告诉我。
推荐阅读
- jdbc - 是否可以使用标准 Db2 Client JAR 连接到 IBM Db2 Event Store?
- mysql - 是否有返回列中名称列表的 MYSql 函数?该字段包含一个逗号分隔的 id 列表
- ruby-on-rails - 返回具有_many 的表C 属于表A 的表B
- matlab - 用 Matlab 模拟温度分布
- java - 如何在 Java Swing 中将 html 文本附加到 JLabel
- ios - 如何通过 bigcommerce 中的 api 获取隐私政策内容以显示在 iOS 中我的 bigcommerce 商店的移动版本中
- wpf - 如何获取列表视图中单元格的行和列索引?
- excel - InputBox 变量在 Countif 公式中未被识别
- python - 如何在 SQLAlchemy 插入语句中指定模式名称?
- vb.net - 未正确读取文本文件