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

Time:12-05

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

Thats my Note models and i need to calculate the notes average to serialize it and send in request resonse

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

And that is my get_queryset redefined method to calculate de average notes, but im just having a list of notes for result of that query, like that: 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']

And this is my serializer

My intencion is try to get an avergate from the exam_notes from the logged user, so i understand that i need to try to group by user_id ant then agregate the average. This is my postgresql table from when im querying: notes_table

I based my code from How to calculate average of some field in Django models and send it to rest API?, but im trying to get some result like as running the following query:

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

CodePudding user response:

To add a GROUP BY functionality, you’ll simply add values to your get_queryset method like this:

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'))
  • Related