django rest-framework
这是我模特的片段:
Class myModel(models.Model)
title = models.CharField(max_length=255,unique=True)
category = models.CharField(max_length=10, choices=CATEGORY)
description = models.CharField(max_length=500)
status = models.CharField(max_length=9, choices=STATUS, default=STATUS[0][0], null=True)
status_update_information=models.CharField(max_length=2000, blank=True, null=True)
creator = models.ForeignKey(User,related_name='Mymodel')
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
状态字段可以有3个值:待处理,已确认和已拒绝。 只有所有者或管理员才能更新对象,但我需要插入一些约束:
当administratop更新状态字段时,我还需要执行其他操作(通知创建者)
为了管理我创建了三个不同的序列化器
一个用于创建模型实例
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = myModel
read_only_fields = ('creator', 'status', 'created_at','updated_at')
def create(self, validated_data):
return super(MyModelSerializer, self).create(validated_data)
def update(self, instance, validated_data):
return super(MyModelSerializer, self).update(instance, validated_data)
如果状态已确认,则用于更新模型
class MyModelConfirmedUpdateSerializer(serializers.ModelSerializer):
class Meta:
model = myModel
fields =['title', 'description']
和一个管理员
class MyModelAdminSerializer(serializers.ModelSerializer):
class Meta:
model = myModel
read_only_fields =('creator', 'created_at', 'updated_at')
def create(self, validated_data):
return super(MyModelAdminSerializer, self).create(validated_data)
def update(self, instance, validated_data):
status = validated_data.get('status')
if status != str(instance.status):
if not validated_data.get('status_update_reason'):
raise serializers.ValidationError(' status update require motivations')
else:
nofitycreator(instance)
return super(MyModelAdminSerializer, self).update(instance, validated_data)
并覆盖Apiview的get_serializer_class方法
def get_serializer_class(self):
serializer_class = self.serializer_class
if self.request.method == 'PUT' or self.request.method == 'PATCH':
if self.request.user.is_staff or self.request.user.is_superuser:
serializer_class = MyModelAdminSerializer
else:
try:
if self.get_object().status == Initiative.STATUS[1][0]:
serializer_class = MyModelConfirmedUpdateSerializer
except:
pass
return serializer_class
有一些聪明的解决方案吗?
如何处理状态字段的部分更新以确保提供status_update_information?