首页 文章

如何在DRF中使用相同名称的read_only和write_only使用不同的序列化程序?

提问于
浏览
2

在DRF的CreateAPI中创建Django对象后,您将获得一个状态201,并返回与您用于创建Django对象的相同序列化程序的对象 .

Wanted: on create:Serializer.comments = Textfield(write_only = True)和on created(201 status)Serializer.comments =一份提交列表

我知道's possible by overriding the CreateAPIView.create function. However, I'想知道是否可以使用 write_only=Trueread_only=True 属性来序列化字段 .

现在我觉得's not possible because they both have the same name. I' d喜欢用假的kwarg名字 actual_name 做这样的事情:

class CreateEventSerializer(serializers.ModelSerializer):
    comments_readonly = serializers.SerializerMethodField(read_only=True, actual_name='comments')

class Meta:
    model = Event
    fields = ('id', 'comments', 'comments_readonly')

def __init__(self, *args, **kwargs):
    super(CreateEventSerializer, self).__init__(*args, **kwargs)
    self.fields['comments'].write_only = True

def get_comments_readonly(self, obj):
    comments = obj.comments.replace('\r', '\n')
    return [x for x in comments.split('\n') if x != '']

但是这样,返回的JSON仍然包含键“comments_readonly”而不是所需的键“comments” .

使用最新的DRF,3.7.1

换句话说:是否可以创建一个基于读写的行为不同的串行器字段(仅使用1个序列化器类)?

1 回答

  • 0

    这似乎是JSON响应的诀窍,但它感觉有点hacky,因为DRF HTML表单现在在注释textarea字段中显示python列表 .

    class CreateEventSerializer(serializers.ModelSerializer):
    
        class Meta:
            model = Event
            fields = ('id', 'comments')
    
        def get_comments(self, obj):
            comments = obj.comments.replace('\r', '\n')
            return [x for x in comments.split('\n') if x != '']
    
        def to_representation(self, instance):
            data = super(CreateEventSerializer, self).to_representation(instance)
            data['comments'] = self.get_comments(instance)
            return data
    

相关问题