DjangoFilters从另一个模型添加过滤器

时间:2018-03-17 18:50:19

标签: python django filter

我将我的DjangoTables类修改为

class Mark_Table(tables.Table):
    teacher = tables.Column(accessor='id_subject.id_teacher.name')
    group = tables.Column(accessor='id_student.id_group.name')
    course = tables.Column(accessor='id_student.id_group.id_course.course')
    curator = tables.Column(accessor='id_student.id_group.curator.name')
    class Meta:
        model = Mark
        fields = ['id_student', 'id_subject','mark' ,'teacher', 'group', 'course', 'curator',]
        attrs = {'class': 'paleblue'}

我有过滤器

class Mark_Filters(filters.FilterSet):
    class Meta:
        model = Mark
        fields = '__all__'

但它们仅适用于模型Mark中的字段。如何在其他模型中添加过滤器,但在同一视图中。我想过滤这个字段: 老师。名称, 组。名称, 课程。课程, 馆长。名称, 是否有任何过滤器或类似的访问器。在DjangoFilters文档中找不到任何内容。提前致谢

My models

1 个答案:

答案 0 :(得分:0)

我找到了答案。模型选择过滤器和模型多选过滤器可以解决我的问题。它看起来像这样。

class Mark_Filters(filters.FilterSet):
teacher_name = filters.ModelChoiceFilter(
    name='id_subject_id__id_teacher__name',
    to_field_name='name',
    queryset=Teacher.objects.all(),
)
group_name = filters.ModelChoiceFilter(
    name='id_student_id__id_group__name',
    to_field_name='name',
    queryset=Group.objects.all(),
)
course = filters.ModelMultipleChoiceFilter(
    name='id_student_id__id_group__id_course__course',
    to_field_name='course',
    queryset=Course.objects.all(),
)
curator_name = filters.ModelChoiceFilter(
    name='id_student_id__id_group__curator',
    to_field_name='curator',
    queryset=Group.objects.all(),



)
class Meta:
    model = Mark
    fields = ['teacher_name', 'id_student', 'id_subject', 'mark', 'course', 'curator_name',]