简体   繁体   English

使用 Django 时如何从我的 json.dumps 文件中恢复整数(用于在我的 javascript 图表中显示)

[英]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.在我的 Django 应用程序中,我有一个非常基本的饼图 model,名称列作为 CharField,统计列作为 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.我的 html 页面上也有一些 javascript 代码,它显示了一个饼图——但只有将这些值硬编码为一个数组,我才能让它工作。 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.我希望将我的模型/数据库中的数据以饼图形式显示为{{ values|safe }} ,从我的数据库数据的 json 转储中提取值。

Here's what I've tried, as seen in my views.py file:这是我尝试过的,如我的views.py文件中所示:

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.在我的 HTML 页面上,我得到的消息只是“无数据”,我相当确定这是因为当我序列化 stats 字段时,它被转换为字符串并且无法被解释为整数。

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]有了这一行piedata=[[pietitle, piestats]] ,如果你想访问第一个标题,你必须 go data_json[0][0][0]并且对于第一批统计数据,你必须 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.如果这是正确的格式,则您可能为 PieChart model 使用了错误的数据类型。 When converting to JSON integers don't get converted to strings.转换为 JSON 时,整数不会转换为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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