Django内联formset通过另一个模型过滤多种关系

时间:2013-05-02 22:54:03

标签: python django django-forms django-admin inline-formset

我有两个模型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模型中移动了循环,现在无法确定如何将过滤器应用到下一个模型。

1 个答案:

答案 0 :(得分:2)

除非我忽略了某些内容,否则您可以使用StudentEnrolmentsInline上的queryset方法执行此操作:

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)