Home > Mobile >  serializing only certain fields from a queryset in django serializer class
serializing only certain fields from a queryset in django serializer class

Time:11-18

I have a queryset which I obtain from get_queryset(). What we know is, the returns of queryset gives the list of objects which contains all the fields of the model. Now I don't want to serialize all the fields from the model and show all of them in the response. I want to serialize only few fields and show in the api response.

for eg:

def get_queryset(self):

    """""
        filtering happens here on the query parameters.
    """
    abc = self.request.GET.get('abc',None)

Now I have a defualt list function where I have to call serializer class only with the specific fields.

def list(self, request, *args, **kwargs):
    
    queryset = self.get_queryset()
    # data ={
    #     "name":queryset.
    # }
    
    # serializer = ExampleSerializer(data,many=True)
    #serializer = serializers.serialize("json",queryset=queryset,fields=['id','name','address'])        
    return Response(serializer, status=status.HTTP_200_OK)

When I do print queryset it gives complex queryset and when I do print(type(queryset)),it gives the following

<class 'django.db.models.query.QuerySet'>

Now how to serialize name and address fields only to the exampleserializer class?? I did some digging and tried to do the following

#serializer = serializers.serialize("json",queryset=queryset,fields=['id','name','address'])

but it does not give the output in the required format not like regular json. Also it gives model: Example in the response of every object.

CodePudding user response:

Did you try this?

queryset = self.get_queryset().values('name', 'address')

CodePudding user response:

I'm not sure I fully understand what you are trying to fetch as your code is incomplete, but it seems that what you need is a ModelSerializer.
get_queryset() should be used to retrieve a queryset of objects that will be used by the serializer thanks to DRF inheritance & mixins system:

# Serializer
class ExampleSerializer(serializers.ModelSerializer):

    class Meta:
        model = Example
        fields = ('id', 'name', 'address')

# View
class ExampleList(ListAPIView):
    serializer_class = ExampleSerializer

    def get_queryset(self):
        return Example.objects.filter(...)

  • Related