[Fixed]-Django JSon response format, nested fields

1👍

You are doing multiple encoding, i.e. first you using serializers.serialize and then json.dumps.

Use only json.dumps and content_type as json like this, without using serializers.

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) .

As you sent content_type=’application/json’, it parse response as json.

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

0👍

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.

Leave a comment