Search code examples
djangodjango-rest-frameworkdjango-querysetdjango-rest-viewsets

Using custom query to return JSON in Django Rest Framework


I started to work with Django rest and I want to know:

Can I make a View or something else to make a custom query and return a JSON?


Solution

  • Yes. Just execute any query you want, convert the data to a dictionary, and return it using a standard response.

    There is no need for a special JsonResponse type of class. You can specify the default renderer in the DEFAULT_RENDERER_CLASSES settings of DRF.

    class MyView(views.APIView):
        def get(self, request):
            data = execute_to_dict(
                 "SELECT a, b FROM x WHERE y = %s AND z = %s"
                 ["yvalue", 73]
            )
            return Response({
                'count': len(data),
                'results': data
            })
    
    
    def execute_to_dict(query, params=None):
        with connection.cursor() as c:
            c.execute(query, params or [])
            names = [col[0] for col in c.description]
            return [dict(list(zip(names, values))) for values in c.fetchall()]
    

    This will output something like:

    { 
        "count": 1, 
        "results": [
            { 
                "a": "value for a", 
                "b": "to be"
            }, 
            { 
                "a": "row 2!", 
                "b": "or not 2 be"
            }
        ]
    }