限制foreign_key的m2m字段的选择



我有这些模型

class SubjectTeacher(models.Model):
teacher = models.ForeignKey(TeacherProfile, on_delete=models.CASCADE)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
SEMESTER_CHOICES = [("1st", "First Quarter"), ("2nd", 'Second Quarter'), ('3rd', 'Third Quarter'), ('4th', 'Fourth Quarter')]
semester = models.CharField(choices = SEMESTER_CHOICES, default = "1st", max_length=3)
students = models.ManyToManyField(StudentProfile, related_name="subjects")
def __str__(self):
return f'{self.subject.subject_name}  | {self.teacher.user.first_name}'
class Meta:
constraints = [
UniqueConstraint(fields = ["teacher", "subject"], name = "Unique Subject Teacher")
]
class StudentGrade(models.Model):
subject_teacher = models.ForeignKey("SubjectTeacher", on_delete=models.CASCADE)
student = models.ForeignKey('StudentProfile', on_delete=models.CASCADE)
grade = models.IntegerField()

现在我想要的是StudentGrade。根据在StudentGrade.subject_teacher

中选择的内容(在django-admin中)来设置student。
Example:
subject_teacher = <subject1> <subject2> 
selected: <subject1>
student = choices from <subject1>.students

我已经尝试过类似的情况,如编辑ModelForm,但我无法得到它的要点。

如果您想使用具有过滤查询集的模型表单,您可以这样做:

# forms.py
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.students = StudentProfile.objects.filter( # your filter )
super(MyForm, self).__init__(*args, **kwargs)
self.fields['students'].queryset = self.students

如果你直接在Django管理中添加StudentGrade,那么它将不知道你想要哪个subject_teacher,而会显示一个包含所有选项的<select>。您需要在启动表单之前指定subject_teacher,以便过滤器按照您想要的方式工作。

相关内容

  • 没有找到相关文章

最新更新