WBA*_*BAR 2 python django django-rest-framework
如何使用 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]
]
}]
Run Code Online (Sandbox Code Playgroud)
对于尝试提出不同方法的用户,我需要说明我需要序列化程序类,因为我想使用generics.ListAPIView并且需要设置serializer_class属性。
您必须创建Field将使用Null值的类:
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)
Run Code Online (Sandbox Code Playgroud)
(因为标准一扔TypeError: float() argument must be a string or a number, not 'NoneType')
现在使用这个序列化程序(诀窍是使用ListField):
class SearchResultSerializer(serializers.Serializer):
id = serializers.IntegerField()
data = serializers.ListField(
child=serializers.ListField(
child=FixedFloatField(
allow_null=True,
required=False,
default=None
)
)
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7994 次 |
| 最近记录: |