DRF Viewset – Return a 400 if object exists and a 200 if it doesn’t

Using Django Rest Framework, I’m trying to create an API endpoint to determine if a given name of an item, already exists.

If it does, then we should let the frontend app know by returning a 400 Bad Request. If it does not exists, then we send a positive 200 OK request.

I find that I can send a 400 just fine but if the item doesn’t exist, I get a 404 that I can do nothign about.

views.py

from rest_framework import viewsets,status
from rest_framework.response import Response
from .serializers import *

class ItemCheckViewSet(viewsets.ModelViewSet):
    """
    The views that are returned when we peform checks against the items
    """
    lookup_field = 'name'
    queryset = Item.objects.all()

    def get_serializer_class(self):
        return ItemSerializer

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)

        if len(serializer.data) > 0:
            return Response("Item already exists", status.HTTP_400_BAD_REQUEST)

        return Response("Item does not exist", status.HTTP_200_OK)

serializers.py

from rest_framework import serializers
from .models import Item


class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = "__all__"

Answer

No need to serialize if the object exists, and you can just check if a Http404 got raised from get_object:

from django.http import Http404


class ItemCheckViewSet(viewsets.ModelViewSet):
    ...
    def retrieve(self, request, *args, **kwargs):
        try:
            instance = self.get_object()
        except Http404:
            return Response("Item does not exist", status.HTTP_200_OK)
        return Response("Item already exists", status.HTTP_400_BAD_REQUEST)