Форматирование данных Django rest API - PullRequest
1 голос
/ 23 мая 2019

Я новичок в Django rest API. Я создаю API для своего проекта, где пользователь может получать данные из системы через API. Я сериализирую данные и передаю также, но я также хочу посчитать результат и передать это значение.

my view.py здесь

    def categorySearch(request, slug):
        itemViewCategory = Item.objects.raw('''select *, company.slug as companySlug, company.name as companyName, 
        field.id as fieldId, field.name as fieldName, category.name as categoryName from company 
        inner join category on company.business_type = category.id inner join category_field on 
        category_field.category_id = category.id inner join custom_field as field on category_field.field_id = field.id 
        where category.id = (select id from category where slug= %s) and field.name LIKE %s order by company.name ''', [slug, product])

        itemViewCategoryCount = Item.objects.raw(
            '''select *, COUNT(company.name) as companyCount from company inner join category on 
             company.business_type = category.id where category.id = (select id from category where slug= %s) 
             order by company.name ''', [slug])

        results = []
        for val in itemViewCategory:
            place_json = {}
            place_json['name'] = val.name
            place_json['email'] = val.email
            place_json['address'] = val.address
            results.append(place_json)
        return JsonResponse(results, safe=False)

где возвращаемые данные вот так

[
    {
        "name": "Washing Plants",
        "email": "ababil.washing@yahoo.com",
        "address": "ababil.washing@yahoo.com"
    },
    {
        "name": "Washing Plants",
        "email": "info@dekkoisho.com",
        "address": "Holding # 79/1, Chandra, Kaliakoir"
    },
    {
        "name": "Washing Plants",
        "email": "aznmery90@yahoo.com",
        "address": "79/8/2 Bibir Bagicha ( 4 No. Gate )\r\nNorth Jatrabari, Dhaka-1205."
    },

]

Но я хочу, чтобы формат данных такого типа

    {

        "statuscode": "0",

        "message": "Success",

        "data": [

            {

            "companyName": "Adorn Knitwear Ltd.",

            "phone": "01713047421",

            "city": "Dhaka"

        },

        {

            "companyName": "Adury Apparels Ltd.",

            "phone": "029333274",

            "city": "Dhaka"

        },

        {

            "companyName": "Advance World Ltd.",

            "phone": "01711537851",

            "city": "Dhaka"

        },

        {

            "companyName": "Afaku Apparels Ltd.",

            "phone": "01711869977",

            "city": "Dhaka"

           }

    ],

    "common": {

        "totalCompany": "104",

    }

}

Теперь, как мне отформатировать мои данные следующим образом?

1 Ответ

2 голосов
/ 23 мая 2019
    for val in itemViewCategory:
            place_json = {}
            place_json['name'] = val.name
            place_json['email'] = val.email
            place_json['address'] = val.address
            results.append(place_json)
   final_result = {}
   final_result['data'] = results
   final_result["statuscode"] = 0
   final_result["message"] = "success"
   return JsonResponse(final_result,safe=False)
...