Reputation: 257
I have a serializer that takes prices and matching transaction dates from a model and sends it on via RetrieveAPIView, to be picked up by a ChartJS price chart on the other end:
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
My problem is that the data is arriving in a jumbled order, as can be seen from the price_dates
here:
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"
]
}
Why is that?
Further details: I've confirmed that the prices and price dates are in order in the model itself. For database, I'm using PostgreSQL11.
Upvotes: 0
Views: 46
Reputation: 11675
You should use order_by
on query to get results in correct order.
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)
Upvotes: 1