即时更改序列化程序字段 [英] Changing serializer fields on the fly

查看:104
本文介绍了即时更改序列化程序字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我有以下序列化器:

  class UserSerializer(serializers.ModelSerializer):

class Meta:
model = User
fields =(
'userid',
'password'

/ pre>

但是我不想在GET上输入密码(当然还有其他字段在我的实例中)。如何编写其他序列化程序?即时更改现场列表。有没有办法这样做?

解决方案

你似乎在寻找一个只写字段。因此,创建时将需要该字段,但根本不会显示给用户(与只读字段相反)。幸运的是,Django REST框架现在支持只写字段, write_only 属性



在Django REST Framework 3.0 中,您只需要添加额外的参数 extra_kwargs 元选项

  class UserSerializer(serializers.ModelSerializer):

类别元:
model =用户
fields =(
'userid',
'密码'

extra_kwargs = {
'密码':{
'write_only':True,
},
}

因为密码应该被哈希(你正在使用Django的用户,对吗?),你将需要也哈希密码将进入。这应该在您的视图中完成,最有可能覆盖 perform_create perform_update 方法。

  from django.contrib.auth.hashers import make_password 

class UserViewSet(viewsets.ViewSet )

def perform_create(self,serializer):
password = make_password(self.request.data ['password'])

serializer.save = password)

def perform_update(self,serializer):
password = make_password(self.request.data ['password'])

serializer.save password = password)

在Django REST Framework 2.x 中,您需要完全重新定义序列化器上的密码字段。

  class UserSerializer serializer.ModelSerializer):
password = serializers.CharField(write_only = True)

class Meta:
mod el = User
fields =(
'userid',
'password'

为了在Django REST Framework 2.x中提前加密密码,您需要覆盖 pre_save

  from django.contrib.auth.hashers import make_password 

class UserViewSet(viewsets.ViewSet):

def pre_save(self,obj,created = False):
obj.password = make_password(obj.password)

super(UserViewSet,self).pre_save(obj,created =创建)






这将解决常见问题其他答案,也就是用于创建/更新用户的同一个串行器也将用于返回更新的用户对象作为响应。这意味着即使您只希望它是只写的密码仍将在响应中返回。这个额外的问题是密码可能或可能不会在响应中散列,这是你真的不想做的。


For example I have the following serializer:

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = (
            'userid',
            'password'
        )

But I don't want to output password on GET (there are other fields in my real example of course). How can I do that without writing other serializer? Change the field list on the fly. Is there any way to do that?

解决方案

You appear to be looking for a write-only field. So the field will be required on creation, but it won't be displayed back to the user at all (the opposite of a read-only field). Luckily, Django REST Framework now supports write-only fields with the write_only attribute.

In Django REST Framework 3.0, you just need to add the extra argument to the extra_kwargs meta option.

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = (
            'userid',
            'password'
        )
        extra_kwargs = {
            'password': {
                'write_only': True,
            },
        }

Because the password should be hashed (you are using Django's user, right?), you are going to need to also hash the password as it is coming in. This should be done on your view, most likely by overriding the perform_create and perform_update methods.

from django.contrib.auth.hashers import make_password

class UserViewSet(viewsets.ViewSet):

    def perform_create(self, serializer):
        password = make_password(self.request.data['password'])

        serializer.save(password=password)

    def perform_update(self, serializer):
        password = make_password(self.request.data['password'])

        serializer.save(password=password)

In Django REST Framework 2.x, you need to completely redefine the password field on the serializer.

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = (
            'userid',
            'password'
        )

In order to hash the password ahead of time in Django REST Framework 2.x, you need to override pre_save.

from django.contrib.auth.hashers import make_password

class UserViewSet(viewsets.ViewSet):

    def pre_save(self, obj, created=False):
        obj.password = make_password(obj.password)

        super(UserViewSet, self).pre_save(obj, created=created)


This will solve the common issue with the other answers, which is that the same serializer that is used for creating/updating the user will also be used to return the updated user object as the response. This means that the password will still be returned in the response, even though you only wanted it to be write-only. The additional problem with this is that the password may or may not be hashed in the response, which is something you really don't want to do.

这篇关于即时更改序列化程序字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆