1

I am using the Django REST Framework and I have a serializer as follows:

class UserProfileSerializer(serializers.ModelSerializer):   
    class Meta:
        model = UserProfile
        depth = 1
        fields = ['user','team','correct','wrong','percentage']

The problem if this passes all user data (including a hashed password). How do I limit the fields being passed?

I have a UserSerializer as follows (which holds the only fields I really want):

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['first_name','last_name','username']

1 Answer 1

5

Instead of depth option declare user field explicitly in UserProfileSerializer and use UserSerializer for this field:

class UserProfileSerializer(serializers.ModelSerializer):   
    user = UserSerializer()
    class Meta:
        model = UserProfile
        fields = ['user','team','correct','wrong','percentage']

Or try to override build_nested_field like this:

class UserProfileSerializer(serializers.ModelSerializer):   
    class Meta:
        model = UserProfile
        depth = 1
        fields = ['user','team','correct','wrong','percentage']

    def build_nested_field(self, field_name, relation_info, nested_depth):
        if field_name == 'user': 
            field_class = UserSerializer
            field_kwargs = get_nested_relation_kwargs(relation_info)

            return field_class, field_kwargs
        return super().build_nested_field(field_name, relation_info, nested_depth) 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.