I manage to get time series data with TruncYear/TruncMonth/TruncDay/etc like below from Tracking table. However the data for the venue just produce the venue_id. I would like to have that serialized so that it returns the "name" from the relation Venue table.
I am using Django 1.11 a postgres 9.4
Here is my time series code:
tracking_in_timeseries_data = Tracking.objects.annotate(
year=TruncYear('created_at')).values('year', 'venue_id').annotate(
count=Count('employee_id',
distinct = True)).order_by('year')
return Response(tracking_in_timeseries_data, status=status.HTTP_200_OK)
currently it output like this:
[
{
"venue_id": 4,
"year": "2017-01-01T00:00:00Z",
"count": 1
},
{
"venue_id": 2,
"year": "2018-01-01T00:00:00Z",
"count": 2
},
{
"venue_id": 6,
"year": "2019-01-01T00:00:00Z",
"count": 1
}
]
I want to explode venue data to return the id & name like this:
[
{
"venue": {
id: 4,
name: "room A"
},
"year": "2017-01-01T00:00:00Z",
"count": 1
},
{
"venue": {
id: 2,
name: "room B"
},
"year": "2018-01-01T00:00:00Z",
"count": 2
},
{
"venue": {
id: 6,
name: "room C"
},
"year": "2019-01-01T00:00:00Z",
"count": 1
}
]
How to explode the "venue" to return the id and name ? The name is useful for presentation purpose.
UPDATE (here are some attempts that failed):
this only displays count but accumulative ( https://gist.github.com/axilaris/0cd86cec0edf675d654eadb3aff5b066). something weird and not sure why.
class TimeseriesSerializer(serializers.ModelSerializer):
venue = VenueNameSerializer(source="venue_id",many=False, read_only=True)
year = serializers.TimeField(read_only=True)
count = serializers.IntegerField(read_only=True)
class Meta:
model = Tracking
fields = ("venue",
"year",
"count")
class TimeseriesSerializer(serializers.Serializer): <-- here is another try but doesnt work serializers.Serializer
venue_id = VenueNameSerializer(many=False, read_only=True)
year = serializers.TimeField(read_only=True)
count = serializers.IntegerField(read_only=True)
I think the answer is quite close to this: django rest framework serialize a dictionary without create a model
FYI, this is my actual code (must as well put it here) for the test, names may differ slightly but the whole intention is the same. https://gist.github.com/axilaris/919d1a20d3e799101a8cf6aeb4d120b5