Ali Raza Javeed
Ali Raza Javeed

Reputation: 155

Record exists or not in DB? Django Api generic Views

I want to write a class based API view to check if the record exists in DB or not then return True else False by using rest_framework. How could I create CBV to check it? Please help me with this context. here is my serializer class

class EmployeeSerializer(ModelSerializer):
class Meta:
    model = Employee
    fields = '__all__'

here is my url

path('employee/<name>/<code>/',views.EmployeeExist.as_view(),name = 'employee_exits')

Upvotes: 0

Views: 83

Answers (1)

Mirza715
Mirza715

Reputation: 420

Here is how you can create simple view:

from rest_framework import status, response
from rest_framework import generics

class EmployeeExistView(generics.GenericAPIView):
   serializer_class = None

   def get(self, request, *args, **kwargs):
       employee = Employee.objects.filter(id=kwargs.get('id'))
       if employee.exists():
           return response.Response(status=status.HTTP_200_OK)
       return response.Response(status=status.HTTP_404_NOT_FOUND)

Upvotes: 1

Related Questions