Home > Software design >  display only some fields in get api response django serializer
display only some fields in get api response django serializer

Time:12-29

I have an example model which has a fk relation with user model and Blog model. Now I have a get api which only requires certain fields of user to be displayed.

My model:

class Example(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        null=True,
        related_name="user_examples",
    )
    blog = models.ForeignKey(
        Blog,
        on_delete=models.CASCADE,
        null=True,
        related_name="blog_examples",
    )
    /................./

Now my view:

class ExampleView(viewsets.ModelViewSet):
    queryset = Example.objects.all()
    serializer_class = ExampleSerializer    

    def list(self, request, *args, **kwargs):
        
        
        id = self.kwargs.get('pk')
        queryset = Example.objects.filter(blog=id)       
        
        serializer = self.serializer_class(queryset,many=True)
        return Response(serializer.data,status=200)

My serializer:

class ExampleSerializer(serializers.ModelSerializer):

class Meta:
    model = Example
    fields = ['user','blog','status']
    depth = 1

Now when I call with this get api, I get all example objects that is required but all the unnecessary fields of user like password, group etc . What I want is only user's email and full name. Same goes with blog, I only want certain fields not all of them. Now how to achieve this in a best way??

CodePudding user response:

You will have to specify the required fields in nested serializers. e.g.

class BlogSerializer(serializers.ModelSerializer):

    class Meta:
        model = Blog
        fields = ['title', 'author']

class ExampleSerializer(serializers.ModelSerializer):
    blog = BlogSerializer()

    class Meta:
        model = Example
        fields = ['user','blog','status']

CodePudding user response:

are you setting depth in serializer's init method or anywhere else? beacause ideally it should only display id's and not anything else. if yes then set depth to zero and use serializer's method field to return data that you need on frontend. I can provide you with example code samples

  • Related