簡體   English   中英

Django Rest Framework:如何序列化列表列表?

[英]Django Rest Framework: How serialize list of list?

如何使用Django Rest序列化程序序列化Floats列表?

我的數據是(我的對象列表的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'

現在使用此序列化器(技巧是使用ListField ):

class SearchResultSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    data = serializers.ListField(
        child=serializers.ListField(
            child=FixedFloatField(
                allow_null=True,
                required=False,
                default=None
            )
        )
    )

您可以使用biult-in json模塊。

data = [{
    '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]
    ]
}]

import json
json_data = json.dumps(data)

您可以將其與DRF視圖混合使用:

from rest_framework.response import Response
...
json_data = json.dumps(data)
return Response(json_data)

編輯

使用ListAPIView

假設您的數據來自名為Mymodel 的模型

# Serializer
from rest_framework import serializers

class MymodelSerializer(serializers.ModelSerializer):

    class Meta:
        model = Mymodel

# View
from rest_framework import generics

class MymodelList(generics.ListAPIView):

    queryset = Mymodel.objects.filter(whatever=whatever)

    def list(self, request):
        # Note the use of `get_queryset()` instead of `self.queryset`
        queryset = self.get_queryset()
        serializer = UserSerializer(queryset, many=True)
        return Response(serializer.data)

取自DRF文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM