简体   繁体   English

Django JSon响应格式,嵌套字段

[英]Django JSon response format, nested fields

I just made an ajax request to a DJango View, it give me back the data, but i don't know how to get only the fields that i want. 我只是向DJango View发出了ajax请求,它给了我数据,但是我不知道如何只获取想要的字段。

This is the part of my view: 这是我观点的一部分:

if request.method == 'POST':
        txt_codigo_producto = request.POST.get('codigobarras_producto') 
        response_data = {} 
            resp_producto=Producto.objects.all().filter(codigobarras_producto=txt_codigo_producto)
            resp_inventario=InventarioProducto.objects.all().filter(producto_codigo_producto__in=resp_producto).order_by('-idinventario_producto')[:1]
            resp_precio=Precio.objects.all().filter(producto_codigo_producto__in=resp_producto,estado_precio=1).order_by('-idprecio')[:1] #

            response_data['codprod']=serializers.serialize('json', list(resp_producto), fields=('codigo_producto')) 
            response_data['inventario']=serializers.serialize('json', list(resp_inventario), fields=('idinventario_producto'))
            response_data['nombre']=serializers.serialize('json', list(resp_producto), fields=('nombre_producto'))
            response_data['valorprod']=serializers.serialize('json', list(resp_precio), fields=('valor_precio'))

            return HttpResponse(
                json.dumps(response_data),
                content_type="application/json"
            )

"json" is the name of the array that I get as response from the view, I send it to the console, as this: “ json”是从视图作为响应获取的数组的名称,将其发送到控制台,如下所示:

console.log(JSON.stringify(json));

And i get this: 我得到这个:

{"codprod":"[{\"model\": \"myapp.producto\", \"fields\": {}, \"pk\": 1}]",
    "nombre":"[{\"model\": \"myapp.producto\", \"fields\": {\"nombre_producto\": \"Pantal\\u00f3n de lona \"}, \"pk\": 1}]",
    "valorprod":"[{\"model\": \"myapp.precio\", \"fields\": {\"valor_precio\": \"250.00\"}, \"pk\": 1}]",
    "inventario":"[{\"model\": \"myapp.inventarioproducto\", \"fields\": {}, \"pk\": 1}]"}

I tried this: 我尝试了这个:

console.log(JSON.stringify(json.codprod));

With that I get this: 这样我得到了:

"[{\"model\": \"myapp.producto\", \"fields\": {}, \"pk\": 1}]" 

But if I try something like json.codprod.pk or json.codprod[0] or json.codprod["pk] I get undefined in the console. 但是,如果我尝试使用json.codprod.pkjson.codprod[0]json.codprod["pk] ,则在控制台中无法undefined

I want to know how to acces to those fields, in "valorprod" I want the "valor_precio" value, so it must be "250.00", in "nombre" I want the value of "nombre_producto" it must be "Pantal\ón de lona". 我想知道如何访问这些字段,在“ valorprod”中我想要“ valor_precio”值,所以它必须是“ 250.00”,在“ nombre”中我想要“ nombre_producto”的值它必须是“ Pantal \\ u00f3n de lona”。

Hope you can give me a hint. 希望你能给我一个提示。 I think this is a JSON syntax problem, but I'm new with this. 我认为这是JSON语法问题,但这是我的新手。


Following Piyush S. Wanare and Roshan instructions, I have made some changes on the view: 按照Piyush S. WanareRoshan指示,我对视图进行了一些更改:

    resp_producto=Producto.objects.filter(codigobarras_producto=txt_codigo_producto)
            resp_inventario=InventarioProducto.objects.filter(producto_codigo_producto__in=resp_producto).order_by('-idinventario_producto')[:1].only('idinventario_producto') 
            resp_precio=Precio.objects.filter(producto_codigo_producto__in=resp_producto,estado_precio=1).order_by('-idprecio')[:1].only('valor_precio') 
            resp_productonombre=Producto.objects.filter(codigobarras_producto=txt_codigo_producto).only('nombre_producto')
            resp_productocodigo=Producto.objects.filter(codigobarras_producto=txt_codigo_producto).only('codigo_producto')

            response_data = {'codprod': resp_productocodigo,'inventario':resp_inventario,'nombre':resp_productonombre,'valorprod':resp_precio}
    return HttpResponse(
            json.dumps(list(response_data)),
            content_type="application/json"
        )

But I get empty fields in the console: 但是我在控制台中得到了空字段:

["nombre","valorprod","codprod","inventario"]

Another edit, and the code that worked: 另一个编辑以及起作用的代码:

I used the views as they was at the beginning, with the double encoding, I just deleted the "codprod" part, but I wrote this on the ajax response code: 我使用了视图,一开始就使用了双重编码,只是删除了“ codprod”部分,但是我在ajax响应代码上写了这些:

var res_valorprod=JSON.parse(json.valorprod);
var res_inventario=JSON.parse(json.inventario);
var res_nombre=JSON.parse(json.nombre);
var campos_valorprod =res_valorprod[0].fields;
var campos_nombre =res_nombre[0].fields;
console.log(res_nombre[0].pk);
console.log(campos_valorprod.valor_precio);
console.log(res_inventario[0].pk);
console.log(campos_nombre.nombre_producto);

This is working, I get what I want, but if you know something better to acces to the multiple nested JSON fields, I will be glad to know it. 这可以正常工作,我可以得到想要的,但是如果您对多层嵌套的JSON字段有更好的了解,我将很高兴知道它。 User dsgdfg gave me a hint. dsgdfg用户给了我一个提示。

You are doing multiple encoding, ie first you using serializers.serialize and then json.dumps. 您正在执行多种编码,即首先使用serializers.serialize,然后使用json.dumps。

Use only json.dumps and content_type as json like this, without using serializers. 像这样,仅使用json.dumps和content_type作为json,而不使用序列化程序。

response_dict = {'your_data_key': 'and your values'}
return HttpResponse(
                json.dumps(response_data),
                content_type="application/json"
            )

and then in client side you are not required to do JSON.stringify(json.codprod) . 然后在客户端,您不需要执行JSON.stringify(json.codprod)

As you sent content_type='application/json' , it parse response as json. 当您发送content_type ='application / json'时 ,它将响应解析为json。

console.log(resp.your_data_key); #will print proper response yor data values.

Answer to your first question:- You can change your queries as follows: 回答第一个问题:-您可以按以下方式更改查询:

resp_producto=Producto.objects.filter(codigobarras_producto=txt_codigo_producto).only('requiredField')
resp_inventario=InventarioProducto.objects.filter(producto_codigo_producto__in=resp_producto).only('requiredField').order_by('-idinventario_producto')[:1]
resp_precio=Precio.objects.filter(producto_codigo_producto__in=resp_producto,estado_precio=1).only('requiredField').order_by('-idprecio')[:1]

Then serialize it. 然后序列化它。

response_data['codprod']=serializers.serialize('json', list(resp_producto), fields=('codigo_producto')) 
            response_data['inventario']=serializers.serialize('json', list(resp_inventario), fields=('idinventario_producto'))
            response_data['nombre']=serializers.serialize('json', list(resp_producto), fields=('nombre_producto'))
            response_data['valorprod']=serializers.serialize('json', list(resp_precio), fields=('valor_precio'))

Suggestion:- It will be better if you create single {} by iterating through each required objects and create list [{},{}] rather than serializing it, and dump it as you have done like, 建议:-如果您通过遍历每个必需的对象并创建列表[{},{}]而不是序列化并按照您的意愿进行转储来创建单个{},那会更好,

return HttpResponse(
                json.dumps(response_data),
                content_type="application/json"
            )

Then at FrontEnd you should use JSON.parse(responceData) for indexing over it. 然后在FrontEnd,您应该使用JSON.parse(responceData)对其进行索引。

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

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