是否有更好的取消嵌套ManyToMany字段唯一检查

时间:2017-08-09 15:20:57

标签: django-rest-framework

# models.py

class Student(models.Model):
    name = models.CharField( max_length=256)
    student_numer = models.CharField(max_length=256)
    teachers = models.ManyToManyField(Teacher)


class Teacher(models.Model):
    name = models.CharField(max_length=256)

# serializers.py

class StudentSerializer(serializers.ModelSerializer):

    class Meta:
        model = Student
        fields = ('name', 'student_number', )


class TeacherSerializer(serializers.ModelSerializer):
    students = StudentSerializer(many=True)

    class Meta:
        model = Teacher
        fields = '__all__'

    def update(self, instance, validated_data):
        students = validated_data.pop('students')

        # here I want delete all old students, and add all new students
        # of course, I have more better way to update it, but here just for simple.

但实际上,如果我更新教师实例,如果学生没有改变,那就会 加注:有这个student_numer的学生已经存在。 我知道为什么,因为StudentSerializer的student_numer字段具有唯一的验证器检查。 我可以添加这样的代码来解决这个问题:

class StudentSerializer(serializers.ModelSerializer):

    class Meta:
        model = Student
        fields = ('name', 'student_number', )
        extra_kwargs = {
            'student_numer': {
                'validators':[]
            }
        } 

现在我想知道还有更好的方法吗?

0 个答案:

没有答案