【问题标题】:DRF serializer change field to read_only for some model instances对于某些模型实例,DRF 序列化程序将字段更改为只读
【发布时间】:2018-09-20 12:08:30
【问题描述】:

我有这个模型:

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')

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

【问题讨论】:

    标签: python django serialization django-rest-framework


    【解决方案1】:

    尝试像这样覆盖__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
    

    【讨论】:

    • 不错!只有什么 - 必须更改 if self.instance and type(self.instance) != TreeQuerySet and self.instance.is_stage: 因为序列化程序同时显示任务列表和单个任务,并在列表视图的情况下引发错误。附言啊,我看到你已经更新了你的答案:)
    【解决方案2】:

    同样的结果可以通过:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-25
      • 2013-09-27
      相关资源
      最近更新 更多