[Answered ]-DRF: How to make serializer fields different depending on instance attributes

1๐Ÿ‘

โœ…

I solved it!

I used the to_representation-function in my serializer like so:

class VisibilityAwareUserSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = get_user_model()
        fields = [
            "id",
            "username",
            "visibility",
            "email",
            "coach",
        ]

    def to_representation(self, instance):
        ret = super(PermissionAwareUserSerializer, self).to_representation(instance)
        fields_to_pop = [
            "email",
            "coach",
        ]
        if not self.userCanSeeObject(self.context['request'].user, instance):
            [ret.pop(field,'') for field in fields_to_pop]
        return ret

    def userCanSeeObject(self, user, obj):
        return ((obj.visibility == "public") or (obj.visibility == "coach" and obj.coach == user or obj == user) or (obj.visibility == "private" and obj == user))

Feel free to point out weaknesses in this solution, but it seems to work well for me.

๐Ÿ‘คSebastian

Leave a comment