需要在 Django 中为我的 API 序列化自定义字段 AVG 注释

Need Serialize a custom filed AVG notes for my API in Django

models.py

from django.db import models
from django.db.models import Avg
from users.models import UserProfile
from subjects.models import Subject


class Note(models.Model):
    id_user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='user_note')
    id_subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='subject_note')
    exam_note = models.IntegerField()

    @property
    def average_note(self):
        if hasattr(self, '_average_note'):
            return self._average_note
        return Note.objects.aggregate(Avg('exam_note'))

那是我的笔记模型,我需要计算笔记平均值以将其序列化并发送请求响应

views.py

class AvgNoteViewSet(viewsets.ModelViewSet):
    serializer_class = AvgSerializer
    authentication_classes = (TokenAuthentication,)
    permission_classes = (NotePermissions,)

    def get_queryset(self):
        return Note.objects.all().annotate(_average_note=Avg('exam_note'))

那是我 get_queryset 重新定义的计算平均音符的方法,但我只是有一个查询结果的音符列表,就像这样: resques response

serializers.py

class AvgSerializer(serializers.ModelSerializer):
    """
    Serializes a notes AVG
    """

    average_note = serializers.SerializerMethodField()

    def get_average_note(self, obj):
        return obj.average_note

    class Meta:
        model = Note
        fields = ['average_note']

这是我的序列化程序

我的意图是尝试从登录用户的 exam_notes 中得到一个平均值,所以我知道我需要尝试按 user_id 蚂蚁分组然后聚合平均的。这是我查询时的 postgresql table:notes_table

我的代码基于 ,但我试图获得一些结果,例如 运行 以下查询:

SELECT avg(exam_note) 
FROM public.notes_note x
group by id_user_id

要添加 GROUP BY 功能,您只需将 values 添加到 get_queryset 方法中,如下所示:

class AvgNoteViewSet(viewsets.ModelViewSet):
    serializer_class = AvgSerializer
    authentication_classes = (TokenAuthentication,)
    permission_classes = (NotePermissions,)

    def get_queryset(self):
        return Note.objects.all().values('id_user').annotate(_average_note=Avg('exam_note'))