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

标签 django django-rest-framework serialization

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

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

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

现在我认为这是不可能的,因为它们都具有相同的名称。
我很想使用假 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 个序列化器类)?

最佳答案

这似乎对 JSON 响应有用,但感觉有点麻烦,因为 DRF HTML 表单现在在注释文本区域字段中显示 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

关于django - 如何在 DRF 中使用相同名称的 read_only 和 write_only 不同的序列化程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46834177/

相关文章:

python - 如何解决安装django-simple-history的问题?

python - 将实例保存到数据库之前/之后是否触发了 Django post_save?

python - 如何在 Django 中模拟 View 装饰器

django - 如何通过 Django 中的 prefetch_related 过滤具有更多条件的反向外键

c++ - 我如何最好地阅读 boost 序列化文件?

python - Django ORM 将数据添加到现有的 JSON 文件中。

django - 使用 django 框架快速入门输入错误

serialization - Avro 替代 Writables

c++ - 编码、数据类型和打包的重复字段

python - 使用 AJAX 在 Django 中更改密码