You want to create a Django view that accepts JSON with a list of numbers under key values, sums them, and returns the sum as JSON. Which code correctly implements this?
hard📝 Application Q15 of 15
Django - REST Framework Basics
You want to create a Django view that accepts JSON with a list of numbers under key values, sums them, and returns the sum as JSON. Which code correctly implements this?
Adef sum_view(request):
data = json.loads(request.body)
total = sum(data['values'])
return JsonResponse({'sum': total})
Bdef sum_view(request):
total = sum(request.POST.getlist('values'))
return JsonResponse({'sum': total})
Cdef sum_view(request):
data = json.dumps(request.body)
total = sum(data['values'])
return JsonResponse({'sum': total})
Ddef sum_view(request):
total = sum(request.GET['values'])
return JsonResponse({'sum': total})
Step-by-Step Solution
Solution:
Step 1: Parse JSON body correctly
Use json.loads(request.body) to get Python dict from JSON input.
Step 2: Sum the list and return JSON response
Extract the list under 'values', sum it, and return with JsonResponse.
Final Answer:
def sum_view(request):
data = json.loads(request.body)
total = sum(data['values'])
return JsonResponse({'sum': total}) -> Option A
Quick Check:
Parse JSON body, sum list, return JsonResponse [OK]
Quick Trick:Parse JSON body, then sum list, then JsonResponse [OK]
Common Mistakes:
MISTAKES
Using json.dumps instead of json.loads
Trying to sum QueryDict values directly
Using request.GET or request.POST for JSON body
Master "REST Framework Basics" in Django
9 interactive learning modes - each teaches the same concept differently