1

view.py

class User_ListView(APIView):
    permission_classes = [DjangoCustomModelPermissions]
    queryset = User.objects.none()

    def get(self, request):
        param1 = request.query_params.get('param1',None) 
        param2 = request.query_params.get('param2',None)

        try:
            db_data = User.objects.get(param1 = param1, param2=param2)
            serializer = User_Serializer(db_data)
            return Response(serializer.data)
        except Closing_Stock_List_Trans.DoesNotExist:
            db_data = User.objects.none()
            serializer = User_Serializer(db_data)
            return Response(serializer.data)

serializer.py

class User_Serializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

I want the serializer to return an empty response when no User DoesNotExist in the User Model, however I get the following error. How can i achieve this?

AttributeError: Got AttributeError when attempting to get a value for field `param1` on serializer `User_Serializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'param1'.

1 Answer 1

2

You are trying to serialize a queryset, so you need to add many=True to the serialization.

....
except Closing_Stock_List_Trans.DoesNotExist:
    db_data = User.objects.none()
    serializer = User_Serializer(db_data, many=True)
    return Response(serializer.data)
Sign up to request clarification or add additional context in comments.

1 Comment

This works, thanks. Just a follow up question. Currently I return status 200 if object is found and if it isnt i return and Empty list as Response. If i have any other error what status should i return, should it be 500?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.