1

我有两个模型 SchoolClass 和 Student,它们通过 Enrollment 模型具有多对多关系。

class Student(models.Model):
    name = models.CharField(max_length=100)
    code = models.CharField(max_length=10)

class SchoolClass(models.Model):
    code = models.CharField(max_length=100)
    cycle = models.ForeignKey(Cycle)
    students = models.ManyToManyField(Student,through='Enrolment')

class Enrolment(models.Model):
    student = models.ForeignKey(Student)
    school_class = models.ForeignKey(SchoolClass)

SchoolClass 模型有一个字段周期(即班级运行的年+学期。当我在管理员中查看学生时,我想查看学生仅在给定周期中注册的课程(例如当前循环)

我之前在 Enrollment 模型中有循环字段,以下效果很好:

class StudentEnrolmentsInlineFormSet(BaseInlineFormSet):
    def get_queryset(self):
        if not hasattr(self, '_queryset'):
            qs = super(StudentInlineFormSet, self).get_queryset().filter(cycle=Current)
            self._queryset = qs
        return self._queryset

class StudentEnrolmentsInline(admin.TabularInline):
    model = Enrolment
    formset = StudentEnrolmentsInlineFormSet

class StudentAdmin(admin.ModelAdmin):
    form = StudentForm
    inlines = (StudentEnrolmentsInline,)

但是,我已经在 SchoolClass 模型中移动了循环,现在无法弄清楚如何将过滤器应用到下一个模型。

4

1 回答 1

2

除非我忽略了某些东西,否则您可以使用querysetStudentEnrolmentsInline 上的方法来执行此操作:

def queryset(self, request):
    current = Cycle.objects.latest() # or whatever to get the current cycle
    qs = super(StudentEnrolmentsInline, self).queryset(request)
    return qs.filter(school_class__cycle=current)
于 2013-05-02T23:35:00.613 回答