1

I trying to filter the list shown when I use the lupe in many to many fields (image bellow). Maybe a text search would be interesting too.

Any help?

django lupe search result example django admin stacked inline example

Here's the code:

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
Ráfagan
  • 2,165
  • 2
  • 15
  • 22

2 Answers2

1

self.model is not QuerySet or a model, use the model directly:

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)

For searching set search_fields for your CourseAdmin:

class CourseAdmin(admin.ModelAdmin):
    search_fields = ('title',)  # your search fields here
Anton Shurashov
  • 1,820
  • 1
  • 26
  • 39
  • How can I use this in a NestedStackedInline? – Ráfagan Aug 03 '17 at 14:16
  • It doesn't depend on `NestedStackedInline`. If you set `search_fields` for the `Course` admin page it will be showed also on [this screen](https://i.stack.imgur.com/w3Sjn.png) – Anton Shurashov Aug 03 '17 at 14:23
  • You're alright. The only limitation is set the queryset for this view, but for filters and search this also apply. Thanks! – Ráfagan Aug 07 '17 at 13:43
1

To make filter in ForeignKeyRawIdWidget (lupe) you need to add a limit_choices_to the widget, it add a query param to filter in popup page like ?type_course=online

Sample:

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
Lucas Paim
  • 417
  • 4
  • 13