Bird
0
0

How can you modify this APIView to return a 404 error if the object with given pk does not exist?

hard📝 Application Q9 of 15
Django - REST Framework Basics
How can you modify this APIView to return a 404 error if the object with given pk does not exist?
class ItemView(APIView):
    def get(self, request, pk):
        item = Item.objects.get(pk=pk)
        return Response({"name": item.name})
AUse filter() instead of get() without error handling
BReplace get() with retrieve() method
CReturn None if item not found
DUse try-except block catching Item.DoesNotExist and return Response with 404 status
Step-by-Step Solution
Solution:
  1. Step 1: Understand get() behavior

    Item.objects.get(pk=pk) raises DoesNotExist exception if no object found.
  2. Step 2: Handle exception properly

    Use try-except to catch DoesNotExist and return Response with 404 status code.
  3. Final Answer:

    Use try-except block catching Item.DoesNotExist and return Response with 404 status -> Option D
  4. Quick Check:

    Handle exceptions to return 404 [OK]
Quick Trick: Catch DoesNotExist and return 404 Response [OK]
Common Mistakes:
MISTAKES
  • Ignoring exceptions causing server errors
  • Using wrong method names
  • Returning None instead of Response

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes