Reputation: 3666
I'm using django-rest-framework. I have a serializer with nested data and I want to hide a specific field (password):
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")
# Other fields related to MyUser model
class Meta:
model = MyUser
fields = ( ..., "password")
write_only_fields = ("password",)
The first problem is that if I remove password from fields
it will error saying that I have password
defined but it's not found in the fields
list.
write_only_fields
does not having any effect on password
; it's always returned.
Is there a way to keep the password for write only and remove it from the result?
Upvotes: 0
Views: 839
Reputation: 1037
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
Upvotes: 0
Reputation: 546
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",)
Upvotes: 0
Reputation: 3666
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.
Upvotes: 1