[Fixed]-Hide nested field from result

1👍

I solved it by removing write_only_fields and modified the field itself to write_only:

password = serializer.CharField(source="user.password", write_only=True).

I have no idea why write_only_fields and extra_kwargs did not work.

👤Ali

0👍

It didn’t work because the write_only_fields attribute of Meta class only overrides the implicit fields (the ones that are only listed in the Meta class fields attributes, and not defined in the ModelSerializer scope) write_only attribute to be True. If you declare a ModelSerializer field explicitly you must define all the attributes that are not default for it to work.

The right code should be something like:

class MyUser(models.Model):
    # django's auth model 
    user = models.OneToOneField(User)

class MyUserSerializer(serializers.ModelSerializer):
    username = serializers.CharField(source="user.username")
    password = serializers.CharField(source="user.password", write_only=True)

    # Other fields related to MyUser model

    class Meta:
        model = MyUser
        fields = ( ..., "password")
        write_only_fields = ("password",)

0👍

You can also override the function that builds the nested fields. Good choice for when you want to display the default auth_user’s name in a nested ListView.

from rest_framework.utils.field_mapping import get_nested_relation_kwargs

def build_nested_field(self, field_name, relation_info, nested_depth):
    """
    Create nested fields for forward and reverse relationships.
    """
    class NestedSerializer(serializers.ModelSerializer):
        class Meta:
            model = relation_info.related_model
            depth = nested_depth - 1
            fields = ['username'] # Originally set to '__all__'

    field_class = NestedSerializer
    field_kwargs = get_nested_relation_kwargs(relation_info)

    return field_class, field_kwargs

Leave a comment