Django Rest Framework - What views to use for simple aggregations?

Viewed 176

I am new to DRF and I am supposed to create few endpoints for only displaying simple statistics data.

What I want:

I want to create simple aggregation endpoint using DRF views, or by any convenient DRF manner.

First endpoint /users/total :

{
    "total_users": 5534
}

Second endpoint /users/2009/january:

{
    "new_users": 12,
    "disabled_users": 2,
    "new_premium_users": 6,
}

Problem:

Looks like the most of the DRF API views are intended to be working good when supplying a list of models, or displaying/manipulating data of single model.

Is there any convenient how to handle simple aggregation endpoints? Any insights appreciated.

1 Answers

Simple example from DRF docs and advanced query example django docs.

class TotalView(APIView):
    """
    get total push it over api
    """
    def get(self, request, format=None):

        total = User.objects.aggregate(
            silver=Sum(
                Case(When(is_silver=True, then=1),
                     output_field=IntegerField())
            ),
            gold=Sum(
                Case(When(is_gold=True, then=1),
                     output_field=IntegerField())
            ),
            platinum=Sum(
                Case(When(is_platinum=True, then=1),
                     output_field=IntegerField())
            )
        )


        return Response({"total": total })

Endpoint:

    {
  "total": {
    "silver": 10,
    "gold": 3,
    "platinum": 15
     }
   }
Related