DRF ModelSerializer将所有字段设为只读,而无需明确指定它们

时间:2019-08-13 10:25:36

标签: python-3.x serialization django-models django-rest-framework

我能够制作只读的模型序列化器,例如:

const styleRow = (state, rowInfo) => {
  if (!rowInfo) return
  return {
    style: {
      borderBottom: rowInfo.index === lastRowIndex? ˋ1px solid;ˋ : ˋˋ
    }
  }
}

但是,我倾向于频繁地向class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = ['name', 'ratio'] read_only_fields = fields 中添加字段或从中删除字段。每次修改Foo时不更新我的序列化器会容易得多。 Foo非常方便:

fields = '__all__'

但是,class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = '__all__' read_only_fields = fields 不接受read_only_fields作为有效选项,并引发以下异常:

__all__

如何在不将每个字段显式添加到Exception Type: TypeError at /api/foo/ Exception Value: The `read_only_fields` option must be a list or tuple. Got str. 列表的情况下将所有字段标记为只读?

1 个答案:

答案 0 :(得分:1)

您可以像这样扩展get_fields方法:

def get_fields(self):
    fields = super().get_fields()
    for field in fields.values():
        field.read_only = True
    return fields