Django 管理过滤器外键组合框

Django admin filter foreign key combobox

我是 django 初学者,所以代码可能是基本的或错误的,但无论如何...... 我有以下型号:

 from django.db import models
    from django.conf import settings

    GRADE_CHOICES = (
        ('1', '1'),
        ('2', '2'),
        ('3', '3'),
        ('4', '4'),
        ('5', '5'),
        ('6', '6'),
        ('7', '7'),
        ('8', '8'),
        ('9', '9'),
        ('10', '10'),
    )
    class Professor(models.Model):
        first_name = models.CharField(max_length=20)
        last_name = models.CharField(max_length=30)

        def __str__(self):
            rta = self.first_name+" "+self.last_name
            return rta

    class Student(models.Model):
        first_name = models.CharField(max_length=20, blank=False, null=False)
        last_name = models.CharField(max_length=30, blank=False, null=False)

        def __str__(self):
            rta = self.first_name+" "+self.last_name
            return rta

    class Subject(models.Model):
        first_name = models.CharField(max_length=50)
        students = models.ManyToManyField(Student, blank=True)
        professors = models.ManyToManyField(Professor, blank=True)

        def __str__(self):
            return self.first_name

    class Grade(models.Model):
        value = models.CharField(choices=GRADE_CHOICES, max_length= 2)
        subject = models.ForeignKey(Grade, on_delete=models.CASCADE, related_name='fk_grade')
        student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='fk_student')

        def __str__(self):
            return self.value

要添加成绩,我需要 select 学科和学生,所以我想根据学生所属的学科过滤学生。 如果学生不在该科目中,则他不应出现在列表中。

我正在使用 django 1.11 和 python 2.7。

您的对象 Grade 不应与 SubjectStudent 相关,而应与 SubjectStudent 之间的关系相关。有点像:

class Professor(models.Model):
    # ...

class Student(models.Model):
    # ...
    professors = models.ManyToManyField(Person, through='Subject')


class Subject(models.Model):
    name = models.CharField(max_length=50)
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    professor = models.ForeignKey(Professor, on_delete=models.CASCADE)
    value = models.CharField(choices=GRADE_CHOICES, max_length= 2)