Reputation: 3115
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.
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)
from rest_framework import serializers
from .models import Item
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = "__all__"
Upvotes: 2
Views: 1155
Reputation: 12068
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)
Upvotes: 2
Reputation: 2627
You can do that with overriding get_object
method. By default this method use get_object_or_404(queryset, **filter_kwargs)
. When this method can't find object, raises Http404 and return 404 status code. But you must watch out for other requestactions e.g post, put. This actions also ask about object the common get_object
method
Upvotes: 1