保存前访问manyToMany字段的值

问题描述 投票:0回答:1

这是我的

Classroom
模型:

class Classroom(models.Model):
    name = models.CharField(max_length=120)
    faculty = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='faculty')
    students = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='students')

    def save(self, *args, **kwargs):
        for faculty in self.faculty.all():
            if not faculty.user_type == 'faculty':
                raise ValidationError('Only users with user type as \'faculty\' can be assigned as faculty to a classroom')
        
        for student in self.students.all():
            if not student.user_type == 'student':
                raise ValidationError('Only users with user type as \'student\' can be assigned as students to a classroom')
        
        return super(Classroom, self).save(*args, **kwargs)

    def __str__(self):
        return self.name

用户模型有一个名为

user_type
的属性,它可以是
faculty
student
。在
Classroom
模型中,我想确保只有 user_type 为教员的用户才能被选为教员,学生也类似。

尝试使用 django admin 添加数据时,我收到以下错误:

ValueError at /admin/classroom/classroom/add/
"<Classroom: Some Class>" needs to have a value for field "id" before this many-to-many relationship can be used.

不知道如何解决,请指导。预先感谢。

django django-models many-to-many manytomanyfield
1个回答
0
投票

经过几个小时的研究,我找到了一个有效的解决方案。我创建了一个新的 Django 表单来创建教室并覆盖了

clean
方法并且它有效。

class ClassroomForm(forms.ModelForm):
    class Meta:
        model = Classroom
        fields = ['name', 'faculty', 'students']
        required = ['name', 'faculty', 'students']

    def clean(self) -> dict[str, Any]:
        if 'faculty' in self.cleaned_data.keys():
            for faculty in self.cleaned_data['faculty']:
                if not faculty.user_type == 'faculty':
                    raise forms.ValidationError(f"Only users with user type as 'faculty' can be assigned as faculty to a classroom. {faculty.email} is not a faculty.")

        if 'students' in self.cleaned_data.keys():
            for student in self.cleaned_data['students']:
                if not student.user_type == 'student':
                    raise forms.ValidationError(f"Only users with user type as 'student' can be assigned as students to a classroom. {student.email} is not a student.")
            
        return super().clean()

将其留在这里,以便对其他人有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.