本文介绍了隐藏GET字段中的密码字段,但在Django REST Framework中隐藏POST字段,其中序列化器中的depth = 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有2种型号:用户&用户摘要。 UserSummary具有用户的外键。我只是注意到,如果在 UserSummarySerializer 内设置 depth = 1 ,则密码字段将包含在输出中。它是经过哈希处理的,但是仍然最好排除该字段。I have 2 models : User & UserSummary. UserSummary has a foreign key to User. I just noticed that if I set depth= 1 within UserSummarySerializer, the password field is included in the output. It's hashed, but it would still be best to exclude this field.要隐藏密码字段,我只是在序列化程序中显式设置了用户字段,就像:To hide the password field, I've just set the user field explicitly in the serializer, just like this :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 userclass UserSummarySerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = models.UserSummary fields = '__all__' depth = 1这种做法的缺点是,在创建新用户时,POST请求中不再提供字段密码。The downside of this way of doing is that, the field password is not available anymore on the POST request when creating a new user.如何隐藏 password 字段,但显示在User的POST请求中?How could I hide the password field on the GET request of UserSummary but display it in the POST request of User ?推荐答案当您将所有功能序列化程序放到一个时,这很复杂,在这种情况下,我将创建一个 UserCreateSerializer :This is complicated when you put all the function serializer to one, I would create a UserCreateSerializer in this scenario:class UserCreateSerializer(serializers.ModelSerializer): """A serializer for our user profile objects.""" class Meta: model = models.User extra_kwargs = {'password': {'write_only': True}} fields = ['username', 'password', 'email', 'firstname', 'lastname', 'mobile'] # there what you want to initial. 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然后,您可以在 UserCreateAPIView 中使用 UserCreateSerializer code>。Then you can use the UserCreateSerializer in your UserCreateAPIView. 这篇关于隐藏GET字段中的密码字段,但在Django REST Framework中隐藏POST字段,其中序列化器中的depth = 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 11-02 21:34