Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework: Retrieving object count from a model

Does anyone know how can I successfully retrieve the object count of a model, in JSON format, and how I need to configure my routing? I'm trying to achieve this using a APIView and returning a Response formatted by JSONRenderer.

UPDATE:

@api_view(['GET'])
@renderer_classes((JSONRenderer, JSONPRenderer))
def InfluenciasCountView(request, format=None):
    influencia_count = Influencia.objects.count()
    content = {'influencia_count': influencia_count}
    return Response(content)

Here's the route I'm using:

url(r'^influencias/count/$', views.InfluenciasCountView, name='influencias-count')
like image 641
Rafael Nascimento Avatar asked Aug 06 '14 03:08

Rafael Nascimento


1 Answers

Check out this snippet of code (the second one). If this does not suit your need, please add some of your code (for better understanding).

UPDATE

For routing, DRF offers a default router for each view. This means that you can have the following configuration in your urls.py: (using the example from the previous link)

url(r'^users/count/$', views. UserCountView.as_view(), name='users-count')

Then, when you access the URL your_base_url/users/count/ you will see something like {'user_count': 10}.

UPDATE 2

The entire code should look like this:

class UserCountView(APIView):
    """
    A view that returns the count of active users.
    """
    renderer_classes = (JSONRenderer, )

    def get(self, request, format=None):
        user_count = User.objects.count()
        content = {'user_count': user_count}
        return Response(content)
like image 148
AdelaN Avatar answered Sep 21 '22 13:09

AdelaN