Django-将模型序列化为json以用作JavaScript对象 [英] Django - serialize models to json for use as JavaScript object
问题描述
我需要从模型中获取数据作为Javascript中的对象.我在JS代码中使用了此代码(数据"是在Django视图中返回的上下文的一部分):
I need to get the data from my models as an object in Javascript. I use this in my JS code ("data" being part of the context returned in my Django view) :
var data= {{ data|safe }};
在我看来,我有:
context = {'data': {
'model1': serializers.serialize('json', model1.objects.all()),
'model2': serializers.serialize('json', model2.objects.all()),
}
我遇到的问题是:
1)除非我在上下文变量上使用安全",否则我在JS中会收到错误消息,
1) I get an error in JS unless I use "safe" on the context variable,
2)即使我使用安全",该对象也无法使用,因为它只是一个字符串(即data.model1 [0]返回"[",而不是数组中的第一个元素).
2) Even if I use "safe", the object is unusable because it is just a string (i.e. data.model1[0] return "[" instead of the first element in the array).
执行此操作的正确方法是什么?
What is the proper way of doing this ?
推荐答案
问题在于,尽管 data
的值是有效的JSON,而 data
本身是一个Python字典,它不能作为JSON来使用.
The trouble is that while the values of data
are valid JSON, data
itself is a Python dict which is not valid as JSON.
最简单的方法可能是将变量分开:
Probably the easiest way to do this would be to separate out the variables:
var data = {
model1: {{ data.model1|safe }},
model2: {{ data.model2|safe }}
}
这篇关于Django-将模型序列化为json以用作JavaScript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!