如何为read_only&提供不同的序列化器在DRF中使用相同名称的write_only?

时间:2017-10-19 16:02:34

标签: django django-rest-framework serializer

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

创建

通缉::Serializer.comments = Textfield(write_only = True) 并在创建(201状态)Serializer.comments =提交列表

我知道可以通过覆盖CreateAPIView.create函数来实现。 但是,我想知道是否可以通过write_only=Trueread_only=True属性使用序列化程序字段来实现。

现在我认为这是不可能的,因为它们都有相同的名称。 我喜欢使用虚假的小名字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"而不是想要的键"评论"。

使用最新的DRF,3.7.1

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

1 个答案:

答案 0 :(得分: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