Jack Grealish
Jack Grealish

Reputation: 21

How to hide field from Json response

I would like to hide from public api simple Serializer field (created without any model). How I can solve this?

same_result = serializers.SerializerMethodField()

Upvotes: 0

Views: 709

Answers (3)

Matthew Hegarty
Matthew Hegarty

Reputation: 4306

I think you could either use the permissions configuration to identify either a public or private user based on membership of a group, then you could switch in the View, something like:

class UserViewSet(viewsets.ViewSet):

    def list(self, request):
        queryset = User.objects.all()
        if request.user.groups.filter(name="private").exists():    
            serializer = PrivateUserSerializer(queryset, many=True)
        else:
            serializer = PublicUserSerializer(queryset, many=True)
        return Response(serializer.data)

Then you define the fields on your serializer as you wish.

Upvotes: 0

Mohamed Beltagy
Mohamed Beltagy

Reputation: 623

you can override the to to_representation method

     def to_representation(self, instance):
      data = super().to_representation(instance)     

      data.pop('same_result')
      return data

Upvotes: 0

Rvector
Rvector

Reputation: 2442

You can use write_only argument to achieve this goal :

class YourSerializer(serializers.Serializer):
    same_result = serializers.SerializerMethodField(write_only=True)

Upvotes: 2

Related Questions