I have models:
class Meter(models.Model):
"""счетчик"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=400)
person = models.ForeignKey(
get_user_model(), on_delete=models.CASCADE, related_name="meters"
)
current_meter_reading = models.IntegerField()
class History(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
date = models.DateField()
meter = models.ForeignKey(to=Meter, on_delete=models.CASCADE, related_name='history')
meter_reading = models.IntegerField()
consumption = models.DecimalField(max_digits=6, decimal_places=2)
type = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(1)])
And serializers for them:
class MeterSerializer(serializers.ModelSerializer):
history = serializers.SlugRelatedField(
many=True,
read_only=True,
slug_field='id'
)
class Meta:
model = Meter
fields = ('id', 'name', 'person', 'current_meter_reading', 'history')
read_only_fields = ('id', 'person')
class HistorySerializer(serializers.ModelSerializer):
class Meta:
model = History
fields = ['date', 'meter', 'meter_reading', 'consumption', 'type']
Now I am trying to write API-endpoit to get list of History model grouped by date,
I would like to retrieve data in format like this:
"data": [
{
"period": "2021",
"consumption": 30,
"value": 110,
"type": null,
"children": [
{
"period": "november",
"consumption": 5,
"value": 110,
"type": null,
"children": [
{
"period": "10.11.2021",
"consumption": 5,
"value": 110,
"type": 0,
"children": []
}
]
},
{
"period": "Сентябрь",
"consumption": 25,
"value": 105,
"type": null,
"children": [
{
"period": "20.09.2021",
"consumption": 15,
"value": 105,
"type": 0,
"children": []
},
{
"period": "10.09.2021",
"consumption": 10,
"value": 90,
"type": 0,
"children": []
}
]
}
]
},
{
"period": "2020",
"consumption": 20,
"value": 80,
"type": null,
"children": [
{
"period": "december",
"consumption": 10,
"value": 80,
"type": null,
"children": [
{
"period": "10.12.2020",
"consumption": 10,
"value": 80,
"type": 0,
"children": []
}
]
},
{
"period": "november",
"consumption": 10,
"value": 70,
"type": null,
"children": [
{
"period": "10.11.2020",
"consumption": 10,
"value": 70,
"type": 0,
"children": []
}
]
}
]
}
]
Also I filtered all History objects that each user can view only History rows related only to him.
And tried to group like this:
histories = History.filter(meter__person=self.request.user)
q = (
histories.annotate(year=TruncYear('date'), month=TruncMonth("date"), day=TruncDay('day')).values("month")
)
return q
But when I try to get this endpoint KeyError appears with this error message:
Got KeyError when attempting to get a value for field
dateon serializer
HistorySerializer.\nThe serializer field might be named incorrectly and not match any attribute or key on the
dict instance.\nOriginal exception text was: 'date'.
"
Please can anyone help how to implement grouping to get data as stated above.