[英]Django inline formset filters in manytomany relationship through another model
I have two models SchoolClass and Student, which have a many-to-many relationship through an Enrolment model. 我有两个模型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)
The SchoolClass model has a field cycle (which is the year+semester that class runs in. When I view a student in the admin, I'd like to see the classes that student is enrolled in only for a given cycle (eg the current cycle) SchoolClass模型有一个字段循环(这是课程运行的年份+学期。当我在管理员中查看学生时,我希望看到学生仅在给定周期内注册的课程(例如当前周期)
I had previously had the cycle field in the Enrolment model, and the following worked nicely: 我以前在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,)
However, I've moved the cycle in the the SchoolClass model, and now can't work out how to apply the filter through to the next model. 但是,我已经在SchoolClass模型中移动了循环,现在无法确定如何将过滤器应用到下一个模型。
Unless I'm overlooking something, you can do this with the queryset
method on StudentEnrolmentsInline: 除非我忽略了某些内容,否则可以使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.