gpt4 book ai didi

python - Django 休息框架 : How serialize list of list?

转载 作者:行者123 更新时间:2023-12-05 09:21:28 26 4
gpt4 key购买 nike

如何使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com