如何在Django Rest Framework中使用PUT方法更新多对多字段

时间:2019-03-14 14:12:12

标签: django python-3.x serialization django-rest-framework

我具有以下模型,并希望在序列化器中创建更新功能。我正在使用的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

0 个答案:

没有答案