Unable to display JsonResponse in Django web project

156 views Asked by At

I am working on a django project. I want to display the result of a query with JsonResponse, but I can only get the raw data, rather than the colourful Json response.

Here is my code

views.py

from django.shortcuts import render
from django.db import connection
from django.http import JsonResponse
import json

# Create your views here.


def index(request):
    return render(request, 'AppTPCC/index.html')


def result(request):
    search_string = request.GET.get('name', '')
    query = 'SELECT * FROM item WHERE i_name ~ \'%s\'' % (search_string)
    c = connection.cursor()
    c.execute(query)
    results = c.fetchall()
    result_dict = {'records': results}
    return render(request, 'AppTPCC/result.html', result_dict)


def query(request):
    query = """ SELECT w.w_country, SUM(s.s_qty) FROM warehouse w, stock s, item i
                WHERE i.i_name = 'Aspirin' AND i.i_id = s.i_id AND w.w_id = s.w_id
                GROUP BY w.w_country; """
    c = connection.cursor()
    c.execute(query)
    results = c.fetchall()
    return JsonResponse(results, safe=False)

urls.py

from django.urls import path, re_path, include
from . import views
urlpatterns = [
    re_path(r'^$', views.index),
    re_path(r'result', views.result),
    re_path(r'query', views.query, name='query'),
]

Then when I type http://127.0.0.1:8000/AppTPCC/query in my browser, I can only get the raw data type. I am wondering how to solve this. Thanks in advance.

0

There are 0 answers