DRF |不能同时设置`read_only`和`write_only`

时间:2019-03-07 06:58:35

标签: django django-rest-framework

在我的项目中,我想将密码设置为let x = -5; let y = -5; for (; x < 5; ++x) { for (; y < 5; ++y) { console.log(x); } }(因为我有一个单独的端点来重置密码)和read_only(因为我不希望在响应中发送密码)。 / p>

这是我的序列化器:

write_only

但是我收到一条错误消息:

  / p / user / 21 /

中的

AssertionError      

不能同时设置class UserSerializer(serializers.ModelSerializer): """A Serizlier class for User """ class Meta: model = models.User fields = ('id', 'email', 'phone_number', 'user_type', 'password') extra_kwargs = { 'password': { 'write_only': True} } read_only_fields = ('password',) 和   read_only

如何让一个字段同时为write_onlyread_only

3 个答案:

答案 0 :(得分:2)

将序列化程序的 __init__() 方法替换为

class UserSerializer(serializers.ModelSerializer):
    """A Serizlier class for User """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.context['some_flag']:
            self.fields['password'].read_only = True
        else:
            self.fields['password'].write_only = True

    class Meta:
        model = models.User
        fields = ('id', 'email', 'phone_number', 'user_type', 'password')
        # extra_kwargs = { 'password': { 'write_only': True} } # remove this
        # read_only_fields = ('password',) # remove this

some_flag 变量是您应该从密码重置视图或其他视图传递给序列化器的东西

答案 1 :(得分:1)

因此扩展了@JPG的答案

序列化器

log_prob

视图集

class ProfileSerializer(serializers.ModelSerializer):
    name = serializers.CharField()

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    if 'create_method' in self.context:
        self.fields['name'].write_only = True
    else:
        self.fields['name'].read_only = True

这将允许名称写在POST上,并且只能在其他所有内容上读取

答案 2 :(得分:0)

好吧-通常,如果您有两个端点使用相似的序列化程序,而这些序列化程序仅需要在特定的字段/功能上有所不同,则可以创建一个基类并对其进行抽象,并且仅更改/修改需要更改的部分。这就是我要做的。

class (serializers.ModelSerializer):
    """A Serizlier class for User """

    class Meta:
        model = models.User
        fields = ('id', 'email', 'phone_number', 'user_type', 'password')
        extra_kwargs = { 'password': { 'read_only': True} }


class UserSerializerForOtherView(UserSerializer):

    class Meta(UserSerializer.Meta):
        extra_kwargs = { 'password': { 'write_only': True} }

现在UserSerializerForOtherView继承了与UserSerializer相同的行为,现在,如果您想进一步扩展此串行器的功能,则现在有了一个新的串行器。

您需要做的就是告诉另一个视图使用另一个序列化器。