Skip to main content
 首页 » 编程设计

python之在 GET 中隐藏密码字段,但在 Django REST Framework 中不隐藏密码字段,其中序列化程序中的深度 = 1

2025年05月04日32zhengyun_ustc

我有 2 个模型:用户和用户摘要。 UserSummary 有一个指向 User 的外键。我刚刚注意到,如果我在 UserSummarySerializer 中设置 depth= 1,密码字段将包含在输出中。它经过哈希处理,但最好还是排除该字段。

为了隐藏密码字段,我只是在序列化程序中明确设置了用户字段,就像这样:

class UserSerializer(serializers.ModelSerializer): 
    """A serializer for our user profile objects.""" 
 
    class Meta: 
        model = models.User 
       extra_kwargs = {'password': {'write_only': True}} 
        exclude = ('groups', 'last_login', 'is_superuser', 'user_permissions', 'created_at') 
 
    def create(self, validated_data): 
        """Create and return a new user.""" 
 
        user = models.User( 
            email = validated_data['email'], 
            firstname = validated_data['firstname'], 
            lastname = validated_data['lastname'], 
            mobile = validated_data['mobile'] 
        ) 
 
        user.set_password(validated_data['password']) 
        user.save() 
 
        return user 
 
 
class UserSummarySerializer(serializers.ModelSerializer): 
    user = UserSerializer() 
 
    class Meta: 
        model = models.UserSummary 
        fields = '__all__' 
        depth = 1 

这种方式的缺点是,在创建新用户时,字段密码在 POST 请求中不再可用。

如何在 UserSummary 的 GET 请求中隐藏 password 字段,但在 User 的 POST 请求中显示它?

请您参考如下方法:

这里的技巧是在“字段”元组中包含“密码”字段,以便密码同时显示在“GET”和“POST”中,然后添加“extra_kwargs”以强制“密码”字段仅出现在'POST' 形式。代码如下:

class UserSerializer(serializers.HyperlinkedModelSerializer): 
    class Meta: 
        model = User 
        fields = ('url', 'username', 'email', 
              'is_active', 'is_staff', 'is_superuser', 'password',) 
 
        # These fields are displayed but not editable and have to be a part of 'fields' tuple 
        read_only_fields = ('is_active', 'is_staff', 'is_superuser',) 
 
        # These fields are only editable (not displayed) and have to be a part of 'fields' tuple 
        extra_kwargs = {'password': {'write_only': True, 'min_length': 4}}