Search code examples
jsondjango-rest-frameworkdjango-serializer

Access JSON values in a DRF API


How can I access "itemnumber" from this serializer?

Or how can I have a better serializer to access data in order_data[id][lot]['Qty'] format

{
    "order_data": {
        "id": [
            {
                "lot": {
                    "itemnumber": "sint ",
                    "Qty": 4
                }
            },
            {
                "lot": {
                    "itemnumber": "occa",
                    "Qty": 2
                }
            }
        ],
    }
}


dt= AddItemsSerializer(data=request.data)
dt.is_valid(raise_exception=True)
order_data = dt.data.get('order_data')

Solution

  • Try this:

    for id_dict in dt.data.get('order_data', {}).get('id', []):
        print(id_dict.get('lot', {}).get('itemnumber'))
    

    It will print out all values of itemnumber.