从结果中隐藏嵌套字段

时间:2016-06-25 09:44:26

标签: django serialization django-rest-framework

我正在使用django-rest-framework。我有一个嵌套数据的序列化程序,我想隐藏一个特定的字段(密码):

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",)

第一个问题是,如果我从fields中删除密码,则说明我已定义password但在fields列表中找不到密码会出错。

write_only_fieldspassword没有任何影响;它总是返回。

有没有办法将密码保留为只写并将其从结果中删除?

3 个答案:

答案 0 :(得分:0)

我通过删除write_only_fields解决了这个问题,并将字段本身修改为write_only:

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

我不知道为什么write_only_fieldsextra_kwargs无效。

答案 1 :(得分:0)

它没有用,因为write_only_fields类的Meta属性只会覆盖隐式字段(仅Metafields中列出的字段属性,并且未在ModelSerializer范围)write_only属性中定义为True。如果明确声明ModelSerializer字段,则必须定义所有非默认值的属性。

正确的代码应该是:

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",)

答案 2 :(得分:0)

您还可以覆盖构建嵌套字段的函数。当您想在嵌套的ListView中显示默认的auth_user名称时,这是一个很好的选择。

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