我具有以下模型,并希望在序列化器中创建更新功能。我正在使用的Http方法是PUT
class Employee(models.Model):
"""
Model, which holds general employment information of an employee in an organization.
"""
user = models.CharField(max_length=100, unique=True, blank=True, null=True)
hr_number = models.CharField(verbose_name='HR number',blank=True, null=True,max_length=20, unique=True)
department = models.ManyToManyField(Department)
unit = models.ManyToManyField(Unit)
到目前为止,这是我对update方法的实现。
class EmployeeDetailSerializer(serializers.ModelSerializer):
department = DepartmentNameSerializer(many=True)
unit = UnitNameSerializer(many=True)
class Meta:
model = Employee
fields = ['hr_number','department','unit']
def update(self, instance, validated_data):
department_data = validated_data.pop('department')
unit_data = validated_data.pop('unit')
instance.hr_number = validated_data.get(
'hr_number',
instance.hr_number
)
department = instance.department
for item in department_data:
# item = dict(item)
department.name = item.get('name',department.name)
return instance