I think this is the pythonic way ("Ask forgiveness, not permission") to check the object existence bu using try..except
clause
def accept(self, request, pk):
try:
Company.objects.get(pk=pk)
return Response({"message": "Success"})
except Company.DoesNotExist:
return Response({"message": "Error"}, status=status.HTTP_405_METHOD_NOT_ALLOWED)
You can find a nice SO post here which ask samething in Django perspective
, which says exists()
is faster than try..except
So, you could rewrite your code something like,
def accept(self, request, pk):
if Company.objects.filter(pk=pk).exists():
return Response({"message": "Success"})
return Response({"message": "Error"}, status=status.HTTP_405_METHOD_NOT_ALLOWED)