作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何使用 Django Rest 序列化器序列化浮点列表列表?
我的数据是(我的对象列表的repr
):
[{
'id': '413',
'data': [
[None, 32.33125, None, None],
[None, 37.96, 48.70112359550562, 66.118],
[None, None, 58.06576923076923, 77.31023809523809],
[None, None, None, 110.0075],
[None, None, None, 139.89]
]
}, {
'id': '406',
'data': [
[None, 35.33125, None, None],
[None, 37.96, 43.123, 66.118],
[None, None, 58.12, 72,123],
[None, None, None, 119.000234],
[None, None, None, 139.89]
]
}]
对于尝试提出不同方法的用户,我需要解释我需要序列化器类,因为我想使用 generics.ListAPIView
并且我需要设置 serializer_class
属性。
最佳答案
您必须创建将使用 Null
值的 Field
类:
class FixedFloatField(serializers.FloatField):
def to_internal_value(self, data):
if data is None:
return data
return super().to_internal_value(data)
def to_representation(self, value):
if value is None:
return value
return super().to_representation(value)
(因为标准的抛出 TypeError: float() argument must be a string or a number, not 'NoneType'
)
现在使用这个Serializer(诀窍是使用ListField
):
class SearchResultSerializer(serializers.Serializer):
id = serializers.IntegerField()
data = serializers.ListField(
child=serializers.ListField(
child=FixedFloatField(
allow_null=True,
required=False,
default=None
)
)
)
关于python - Django 休息框架 : How serialize list of list?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32214837/
我是一名优秀的程序员,十分优秀!