[Fixed]-JSON Dump of raw SQL query returning empty dictionary

0👍

Okay after playing around for a bit, I finally fixed it. My problem was that I needed to search for an exact string name in one of the tables and columns in my database but I was retrieving my sent data in views.py as a query dictionary. The thing is that this query dictionary had my single string that I passed in through my request as the key of the dictionary, not the value. So i needed to convert it into a single string variable then use my query. I also needed to not have the ‘ ‘ around my %s inside the query.

Views.py:

def getData(request):
   some_data = request.GET
   for key in some_data:
        SWVALUE = key
   cursor = connection.cursor()
   cursor.execute("SELECT SW_ID FROM sw WHERE SWName = %s ", (SWVALUE))
    = %s ", %ItemfromSW)
   row = cursor.fetchall()
   json_data = json.dumps(list(row))
   return HttpResponse(json_data, content_type = "application/json")
👤Carbon

1👍

Have you tried to print “row” variable? Is there any result?
Because maybe this is not a problem from the query, but the problem is that row data is not json serializable, and so JsonResponse can’t render it.

i. e., I believe cursor.fetchall() will deliver your data in the following format: [(1,),(5,),(7,)], because it returns a list of tuples. And when you call list(row), response is the same (as a list of tuples is already a list).

Just to be sure, try this:

def getData(request):
   some_data = request.GET.get('selectionvalue')
   cursor = connection.cursor()
   cursor.execute("SELECT SW_ID FROM sw WHERE SWName = %s ", [some_data])
   row = cursor.fetchall()

   items = []
   for r in row:
      items.append(r[0])

   return JsonResponse({"Item" : items})

Leave a comment