gpt4 book ai didi

python - 对于某些模型实例,DRF 序列化程序将字段更改为 read_only

转载 作者:太空宇宙 更新时间:2023-11-04 02:17:07 24 4
gpt4 key购买 nike

我有这个模型:

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' 变为只读>。我该怎么做?

最佳答案

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

关于python - 对于某些模型实例,DRF 序列化程序将字段更改为 read_only,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52424854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com