如何在django串行化器中计算日平均值

lf5gs5x2  于 2023-01-27  发布在  Go
关注(0)|答案(1)|浏览(145)

我的模特:

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()

我的序列化器:

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

我的看法:

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

我在同一天有多条记录,我需要计算平均值,每天只返回一条记录

vi4fp9gy

vi4fp9gy1#

要获取给定日期时间的记录的平均值:

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')}

您可以查看Django documentation以了解更多关于聚合的信息。

相关问题