menu

Questions & Answers

How to calculate daily average in django serializer

my model :

class Record(models.Model):
        type = models.CharField(max_length=9, choices=RECORD_CHOICES)
        user = models.ForeignKey(User,on_delete=models.CASCADE)
        record = models.DecimalField(decimal_places=4,max_digits=8)
        date_time = models.DateTimeField()
   

my serializer:

 class RecordSerializer_1(serializers.ModelSerializer):
    class Meta:
        model = Record
        fields = ['type','record','date_time']

my view :

  records = Record.objects.filter(user=user,type="HeartRate")
        serializer = RecordSerializer_1(records, many=True)

I have more than one record at same day , I need to calculate average and return only one record per day

Comments:
2023-01-23 00:55:04
So you want to calculate an average over records on the same day, but what record will you return? The resulting average might be a decimal which is not a record.
Answers(1) :

To get the average of a record given datetime:

from django.db.models import Avg

# Ex records:
records = [2, 3, 4, 7, 9]

day = datetime.datetime.now()
agg = Record.objects.filter(date_time=day).aggregate(record_average=Avg("record"))
# {'record_average': Decimal('5')}

You can have a look at the Django documentation for more about aggregation.