Bird
0
0

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:
  1. Step 1: Parse JSON body correctly

    Use json.loads(request.body) to get Python dict from JSON input.
  2. Step 2: Sum the list and return JSON response

    Extract the list under 'values', sum it, and return with JsonResponse.
  3. Final Answer:

    def sum_view(request): data = json.loads(request.body) total = sum(data['values']) return JsonResponse({'sum': total}) -> Option A
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes