Yann Btd
Yann Btd

Reputation: 419

Django Serializers - Return the sum of values by filter

Following this post: Serializer - Django REST Framework - The serializer field might be named incorrectly and not match any attribute or key on the `str` instance

I use this function:

def get_month_hours(self):
    last_year = timezone.now() - datetime.timedelta(days=365)  # for more accurate result, please use python-dateutil or similar tools
    return Timesheet.objects.annotate(total_hour=Sum('working_hour')).filter(owner=self.user, date__gte=last_year).order_by('date')

I want to populate the chart who use exactly the same code:

"data": [65, 59, 80, 81, 56, 55, 40],

All values corresponding to the total working_hours (my models field) per month.

So, I have 2 problems: The first, I receive this data:

 {
    "id": 3,
    "title": "Développement intranet",
    "date": "2018-11-19",
    "working_hour": 8.5,
    "week": 47,
    "owner": 1
},
{
    "id": 1,
    "title": "Développement intranet",
    "date": "2018-11-26",
    "working_hour": 8.5,
    "week": 48,
    "owner": 1
},
{
    "id": 2,
    "title": "Développement intranet",
    "date": "2018-11-27",
    "working_hour": 8.5,
    "week": 48,
    "owner": 1
},
{
    "id": 4,
    "title": "dev python",
    "date": "2018-11-28",
    "working_hour": 5.25,
    "week": 48,
    "owner": 1
},
{
    "id": 5,
    "title": "Développement intranet",
    "date": "2018-12-03",
    "working_hour": 8.5,
    "week": 49,
    "owner": 1
}

But I want to receive only one value: the sum of working_hour per month.

The second problme is: how to pass this values to my "data" ? I thinked like that: "data" : $.ajax({ url: '/my-json-url/', method: 'get', }),

right ?

thanks per advance

Upvotes: 1

Views: 1590

Answers (1)

Ngoc Pham
Ngoc Pham

Reputation: 1458

for first, you can try like this:

    return Timesheet.objects.annotate(total_hour=Sum('working_hour')).filter(owner=self.user, date__gte=last_year).order_by('date')
.values_list('total_hour', flat=True)

this will give you array data of total_hour

in api view from enter link description here you must edit

@api_view(['GET'])
def timesheet_total_per_month(request):
    hours = ReturnHour(request.user.pk, datetime.datetime.now().isocalendar()[1])
    timesheets = hours.get_month_hours()
    return Response({'data':timesheets})

Upvotes: 1

Related Questions