来自Django视图的JSON数据

时间:2017-11-11 23:53:23

标签: python json django

我想查询数据库中的一行表,并从Django视图以JSON格式发送此数据:我检查了Django serializer for one object,我想出了:

class BaseView(TemplateView):
    def get_context_data(self, **kwargs):
        context = super(BaseView, self).get_context_data(**kwargs)

        data = Language.objects.get(id=1)
        array_result = serializers.serialize('json', [data], ensure_ascii=False)
        context['oneLanguageItemInJSON'] = array_result[1:-1]


        return context

但它发送的对象如下:

"{
    "fields": 
        {"prop1": "val1", 
        "prop2": "value2", 
        "prop3": "val3"
        }, 
    "model": "front.language", 
    "pk": 1
}"

任何人都知道可以在这里做些什么来获得普通的JSON对象?

编辑: 如果我这样做:

data = Language.objects.get(id=1)
dict_obj = model_to_dict( data )
context['oneLanguageItemInJSON'] = json.dumps(dict_obj)

结果是:

<CustomFieldImg:2017-11-10_19-10-57_c64a-11e7-b6ab-8c53f931.png> is not JSON serializable

否则,如果我这样做:

    data = Language.objects.get(id=1)
    context['oneLanguageItemInJSON'] = json.loads(data)

我明白了:

expected string or buffer

并且:

    data = Language.objects.get(id=1)
    context['oneLanguageItemInJSON'] = json.dumps(data, cls=DjangoJSONEncoder)

结果是:

<Language: English> is not JSON serializable

- «英语»是属性«语言»的值,存储在模型中 -

有什么想法吗?

解决方案:在视图中:

    language = Language.objects.get(id=1)
    results = serializers.serialize('json', [language], ensure_ascii=False).encode('utf8')
    # Convert JSON string to list of dicts
    data = json.loads(results)[0]
    # Extract the fields
    fields = data['fields']
    # Convert fields back to JSON string
    fields_as_json = json.dumps(fields)
    context['oneLanguageItemInJSON'] = fields_as_json

在模板中

  oneLanguageItemInJSON: [{{ oneLanguageItemInJSON|safe }}]

括号对于创建数组很重要。

2 个答案:

答案 0 :(得分:0)

您可以使用Django Rest Framework。 http://www.django-rest-framework.org/#

查看快速入门指南以及如何使用模型序列化程序。

答案 1 :(得分:0)

如果通过&#34;正常&#34;你的意思是你只想要字段,这可能有效:

language = Language.objects.get(id=1)
results = serializers.serialize('json', [language], ensure_ascii=False)
# Convert JSON string to list of dicts and grab the first dict (which
# corresponds to `language`)
data = json.loads(results)[0]
# Extract the fields
fields = data['fields']

# Convert fields back to JSON string
fields_as_json = json.dumps(fields)
context['oneLanguageItemInJSON'] = fields_as_json

替代结尾(跳过转换回JSON字符串并在模板中使用jsonify):

context['oneLanguageItemInJSON'] = fields