Home > Blockchain >  Get sum of nested JSON
Get sum of nested JSON

Time:10-21

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

CodePudding user response:

I will wager a guess and say you want something like

 User.objects.annotate(Sum('logs__work_hours'))
  • Related