Get sum of nested JSON

Question:

I have this JSON data where "logs" is called as another serializer.

{
    "id": 1,
    "logs": [
        {
            "work_hours": 7,
            "user": "admin"
        },
        {
            "work_hours": 8,
            "user": "admin"
        },
        {
            "work_hours": 6,
            "user": "admin"
        },
        {
            "work_hours": 4,
            "user": "admin"
        },
        {
            "work_hours": 5,
            "user": "admin"
        }
    ]
}

Is it possible to get the total work_hours from logs? Tried the annotate(Sum) but I can only get the Sum of logs.id as default

Here is my serializer.py

class UserLogsSerializer(serializers.ModelSerializer):

    user = serializers.StringRelatedField()
    class Meta:
        model=UserLogs
        fields=['work_hours','user']

class UserSerializer(serializers.ModelSerializer):
    logs = UserLogsSerializer(read_only=True,many=True)

    class Meta:
        model=User
        fields='__all__'
Asked By: Marjoe Manicad

||

Answers:

I will wager a guess and say you want something like

 User.objects.aggregate(Sum('logs__work_hours'))

OR

User.objects.aggregate(hours_worked=Sum('logs__work_hours'))

And then it will be accessible on all objects in the queryset as if it was a declared property or field.

Answered By: Swift