DRF序列化程序将某些模型实例的字段更改为只读

时间:2018-09-20 12:08:31

标签: python django serialization django-rest-framework

我有这个模型:

class Task(MPTTModel, TimeStampedModel, StartFinishModel):
    name = models.CharField(max_length=256)
    parent = TreeForeignKey('self',
                            on_delete=models.CASCADE,
                            related_name='children')
    start_date = models.DateField()    
    finish_date = models.DateField()
    @property
    def is_stage(self):
        if self.get_children():
            return True
        return False

和序列化器:

class TaskBaseSerializer(StartFinishSerializer, TimeStampedSerializer):
    class Meta:
        model = Task
        fields = ('id', 'name', 'parent', 'start_date', 'finish_date', 'is_stage')    
        read_only_fields = ('is_stage')

如果'start_date'属性为 True ,我想使字段'finish_date'is_stage变为只读。我该怎么办?

2 个答案:

答案 0 :(得分:2)

尝试像这样重写__init__()方法:

class TaskBaseSerializer(StartFinishSerializer, TimeStampedSerializer):
    class Meta:
        model = Task
        fields = ('id', 'name', 'parent', 'start_date', 'finish_date', 'is_stage')    
        read_only_fields = ('is_stage')

    def __init__(self, *args, **kwargs):
        super(TaskBaseSerializer, self).__init__(*args, **kwargs)
        if self.instance and getattr(self.instance, 'is_stage', None):
            self.fields['start_date'].read_only = True
            self.fields['finish_date'].read_only = True

答案 1 :(得分:0)

使用以下方法也可以达到相同的结果

def get_fields(self):
    fields = super(TaskBaseSerializer, self).get_fields()
    if self.instance and getattr(self.instance, 'is_stage', None):
        fields['start_date'].read_only = True
        fields['finish_date'].read_only = True
    return fields