Skip to content
Advertisement

How to return empty queryset from serializer.data Django Rest Framework

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'.

Advertisement

Answer

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)

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement