简体   繁体   中英

How to restore integers from my json.dumps file (for display in my javascript chart) when using Django

In my Django application, I have a very basic Pie Chart model with the name column as a CharField and the stats column as an IntegerField. I also have some javascript code on my html page that displays a pie chart -- but I'm only able to get it working if I hardcode the values as an array. I was hoping to instead display the data from my model/ DB as {{ values|safe }} in pie chart form, pulling the values from json dumps of my DB data.

Here's what I've tried, as seen in my views.py file:

def metrics(request):
    pietitle = serializers.serialize('json', PieChart.objects.all(),fields=('title'))
    piestats = serializers.serialize('json', PieChart.objects.all(),fields=('stats'))
    piedata=[[pietitle, piestats]]
    json_data = json.dumps(piedata) 
    data_json= json.loads(json_data)
    return render(request, "metrics.html", {"values": data_json})

On my HTML page, the message I'm getting is simply "No Data", and I'm fairly certain that's because when I serialize the stats field, it's converted to a string and is unable to be interpreted as integers.

Would anyone kindly be able to assist? Thanks so much, in advance.

Make sure the data is in the correct format for the pie chart.

With this line piedata=[[pietitle, piestats]] , if you wanted to access the first title you'd have to go data_json[0][0][0] and for the first lot of stats you'll have to go data_json[0][1][0]

Edit:

If this is the correct format, it is possible you are using the wrong datatype for the PieChart model. When converting to JSON integers don't get converted to strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM