来自 RetrieveAPIView 的序列化数据杂乱无章地到达

Serialized data from RetrieveAPIView arriving jumbled

我有一个序列化程序,它从模型中获取价格和匹配的交易日期,并通过 RetrieveAPIView 将其发送,以供另一端的 ChartJS 价格图表获取:

class MyPriceSerializer(serializers.Serializer):
    prices = serializers.SerializerMethodField()
    price_dates = serializers.SerializerMethodField()

    def get_prices(self, obj):
        return obj.prices.values_list('price', flat=True)

    def get_price_dates(self, obj):
        qs = obj.prices.all()
        qs = qs.extra(select={'datestr':"to_char(price_date, 'DD Mon HH24:MI')"})
        return qs.values_list('datestr', flat=True)

class ChartData(RetrieveAPIView):
    queryset = Market.objects.all().prefetch_related('prices')
    authentication_classes = []
    permission_classes = []
    serializer_class = MyPriceSerializer

我的问题是数据以混乱的顺序到达,从price_dates这里可以看出:

HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "prices": [
        0.55,
        0.57,
        0.5,
        0.43,
        0.45,
        0.57,
        0.55,
        0.48,
        0.4,
        0.52,
        0.6,
        0.52,
        0.45,
        0.43
    ],
    "price_dates": [
        "24 Jul 12:08",
        "24 Jul 12:08",
        "24 Jul 12:08",
        "24 Jul 12:09",
        "24 Jul 12:11",
        "24 Jul 12:08",
        "24 Jul 12:08",
        "24 Jul 12:08",
        "24 Jul 12:09",
        "24 Jul 12:08",
        "24 Jul 12:08",
        "24 Jul 12:08",
        "24 Jul 12:08",
        "24 Jul 12:09"
    ]
}

这是为什么?

更多详细信息:我已确认价格和价格日期在模型本身中是有序的。对于数据库,我使用的是 PostgreSQL11。

您应该在查询中使用 order_by 以获得正确顺序的结果。

    def get_prices(self, obj):
        return obj.prices.order_by('price_date').values_list('price', flat=True)

    def get_price_dates(self, obj):
        qs = obj.prices.all().order_by('price_date')
        qs = qs.extra(select={'datestr':"to_char(price_date, 'DD Mon HH24:MI')"})
        return qs.values_list('datestr', flat=True)