Q:

Most simple way to check object exist and give responce

I have a code snippet which repeats several times in my ViewSets:
def accept(self, request, pk):
    if not Company.objects.filter(pk=pk).exists():
        return Response({"message": "Error"},
                        status=status.HTTP_405_METHOD_NOT_ALLOWED)

It looks like I'm doing this too complex. Is it a way to make it simpler? Thanks!

A:

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)

