我有一个序列化器,该序列化器从模型中获取价格和匹配的交易日期,并通过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。
答案 0 :(得分:1)
您应在查询中使用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)