如何在 Django 中格式化 json 响应?

How to format json response in django?

我正在从 Django 中的多个表中检索数据。 我目前的回复是:

{
    "status": 0,
    "message": "Client details retrived successfully...!!!",
    "results": [
        {
            "id": 11,
            "client_id": "CL15657917080578748000",
            "client_name": "Pruthvi Katkar",
            "client_pan_no": "RGBB004A11",
            "client_adhar_no": "12312312313",
            "legal_entity_name": "ABC",
            "credit_period": "6 months",
            "client_tin_no": 4564565,
            "client_email_id": "abc@gmail.com",
            "head_office_name": "ABC",
            "office_name": "asd234",
            "office_email_id": "zxc@gmail.com",
            "office_contact": "022-27547119",
            "gst_number": "CGST786876876",
            "office_country": "India",
            "office_state": "gujrat",
            "office_district": "vadodara",
            "office_taluka": "kachh",
            "office_city": "vadodara",
            "office_street": "New rode 21",
            "office_pincode": 2344445,
            "contact_person_name": "prasad",
            "contact_person_designation": "DM",
            "contact_person_number": "456754655",
            "contact_person_email": "asd@gmail.com",
            "contact_person_mobile": "5675545654",
            "created_at": "2019-08-14T14:08:28.057Z",
            "created_by": "Prathamseh",
            "updated_at": "2019-08-14T14:08:28.057Z",
            "updated_by": "prasad",
            "is_deleted": false
        },
        {
            "id": 11,
            "user_id": "CL15657917080578748000",
            "bank_details_id": "BL15657917080778611000",
            "bank_name": "Pruthvi",
            "branch": "vashi",
            "ifsc_code": "BOI786988",
            "account_number": 56756765765765,
            "account_name": "Pruthvi",
            "is_deleted": false
        },
        {
            "id": 10,
            "document_details_id": "DL15657917080808598000",
            "user_id": "CL15657917080578748000",
            "document_type": "Pruthvi ID",
            "document": "www.sendgrid.com/pan",
            "is_deleted": false
        }
    ]
}

预期响应:

我正在 models.py 中获取查询集表单数据库,并将其发送到 views.py,我正在遍历字典,但没有得到预期的响应。

views.py

@csrf_exempt
def get_client_details(request):
    try:
        # Initialising lists for storing results
        result      =   []
        temp_array  =   []
        # Getting data from request body
        client_master_dict = json.loads(request.body)
        # Response from get client data
        records = ClientDetails.get_client_data(client_master_dict)
        # Create response object
        # Iterating over the records object for getting data
        for i in range(len(records)):
            # Converting the querysets objects to json array format
            record_result_list  = list(records[i].values())
            # If multiple records are present
            if(len(record_result_list) > 1):
                for j in range(len(record_result_list)):
                    user_info = record_result_list[j]
                    temp_array.append(user_info)
                result.append(temp_array)   
                temp_array=[] 
            # For single record     
            else:
                result.append(record_result_list[0])
        # Success  
        returnObject = {
            "status"    :   messages.SUCCESS,
            "message"   :   messages.CLIENT_RETRIVE_SUCCESS,
            "results"   :   result
        }
        return JsonResponse(returnObject,safe=False)

我认为问题可能出在我内部的 for 循环中,任何人都可以帮我解决这个问题,有没有什么方法可以遍历嵌套的 JSON 对象。

Models.py

@classmethod
    def get_client_data(cls, client_master_dict):  
        try:        
            response_list = []
            client_id = client_master_dict['client_id']
            client_details = cls.objects.filter(client_id = client_id,is_deleted = False)
            bank_details = BankDetails.objects.filter(user_id = client_id,is_deleted = False)
            document_details = DocumentDetails.objects.filter(user_id = client_id,is_deleted = False)
            response_list.append(client_details)
            response_list.append(bank_details)
            response_list.append(document_details)
            return response_list
        except(Exception) as error:
            print("Error in get_client_data",error)
            return False 

这里我从 3 个表中获取数据并将其添加到列表中。

在控制台上打印数据后,我得到:

[{'id': 11, 'client_id': 'CL15657917080578748000', 'client_name': 'Pruthvi Katkar', 'client_pan_no': 'RGBB004A11', 'client_adhar_no': '12312312313', 'legal_entity_name': 'ABC', 'credit_period': '6 months', 'client_tin_no': 4564565, 'client_email_id': 'abc@gmail.com', 'head_office_name': 'ABC', 'office_name': 'asd234', 'office_email_id': 'zxc@gmail.com', 'office_contact': '022-27547119', 'gst_number': 'CGST786876876', 'office_country': 'India', 'office_state': 'gujrat', 'office_district': 'vadodara', 'office_taluka': 'kachh', 'office_city': 'vadodara', 'office_street': 'New rode 21', 'office_pincode': 2344445, 'contact_person_name': 'prasad', 'contact_person_designation': 'DM', 'contact_person_number': '456754655', 'contact_person_email': 'asd@gmail.com', 'contact_person_mobile': '5675545654', 'created_at': datetime.datetime(2019, 8, 14, 14, 8, 28, 57874, tzinfo=<UTC>), 'created_by': 'Prathamseh', 'updated_at': datetime.datetime(2019, 8, 14, 14, 8, 28, 57874, tzinfo=<UTC>), 'updated_by': 'prasad', 'is_deleted': False}]
[{'id': 11, 'user_id': 'CL15657917080578748000', 'bank_details_id': 'BL15657917080778611000', 'bank_name': 'Pruthvi', 'branch': 'vashi', 'ifsc_code': 'BOI786988', 'account_number': 56756765765765, 'account_name': 'Pruthvi', 'is_deleted': False}]
[{'id': 10, 'document_details_id': 'DL15657917080808598000', 'user_id': 'CL15657917080578748000', 'document_type': 'Pruthvi ID', 'document': 'www.sendgrid.com/pan', 'is_deleted': False}]

你检查过record_result_list的输出了吗?您可以直接告诉他们是否正在以您请求的格式恢复数据。尝试打印到屏幕的方法进行调试。

据我所知,银行详细信息的预期输出和结果层次结构不匹配。我不知道你是如何处理层次结构的。你是直接从JSON拿来当层级吗?或者您只是获取数据并在预期输出中创建层次结构?