如何在多个到多个字段中自定义django管理搜索结果

时间:2017-08-02 21:00:03

标签: python django admin

我尝试过滤当我在许多字段中使用lupe时显示的列表(图像低于)。 也许文本搜索也会很有趣。

任何帮助?

django lupe search result example django admin stacked inline example

以下是代码:

class PresentialModuleCourseInline(NestedStackedInline):
    """Module Course Presential Stacked Inline"""
     model = Course.modules.through
     raw_id_fields = ('module_course',)
     extra = 1

     def get_queryset(self, request):
        return self.model.objects.filter(
           module_course__type_course=ModuleCourse.PRESENTIAL)  # Doesn't work

2 个答案:

答案 0 :(得分:1)

self.model不是QuerySet或模型,请直接使用该模型:

class PresentialModuleCourseInline(NestedStackedInline):
     model = Course.modules.through
     raw_id_fields = ('module_course',)
     extra = 1

     def get_queryset(self, request):
        return Course.objects.filter(module_course__type_course=ModuleCourse.PRESENTIAL)

search_fields搜索集CourseAdmin

class CourseAdmin(admin.ModelAdmin):
    search_fields = ('title',)  # your search fields here

答案 1 :(得分:1)

要在ForeignKeyRawIdWidget(lupe)中进行过滤,您需要向窗口小部件添加limit_choices_,它会添加一个查询参数,以便在弹出页面中进行过滤,例如?type_course=online

样品:

class PresentialModuleCourseInline(NestedStackedInline):
"""Module Course Presential Stacked Inline"""
model = Course.modules.through
extra = 1
raw_id_fields = ('module_course', )

def get_formset(self, request, obj=None, **kwargs):
    form = super().get_formset(request, obj, **kwargs)
    field = form.form.base_fields['module_course']
    field.widget.rel.limit_choices_to =\
        {'type_course': ModuleCourse.PRESENTIAL}
    return form