Reputation: 2323
I am new in Django rest API. I create an API for my project where user can get data from the system via API. I serialize data and pass also but I also want to count the result and pass that value too.
my view.py is here
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)
where its return data like this
[
{
"name": "Washing Plants",
"email": "[email protected]",
"address": "[email protected]"
},
{
"name": "Washing Plants",
"email": "[email protected]",
"address": "Holding # 79/1, Chandra, Kaliakoir"
},
{
"name": "Washing Plants",
"email": "[email protected]",
"address": "79/8/2 Bibir Bagicha ( 4 No. Gate )\r\nNorth Jatrabari, Dhaka-1205."
},
]
But I want this type of data formate
{
"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",
}
}
Now how can I format my data like this?
Upvotes: 1
Views: 224
Reputation: 27553
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)
Upvotes: 2