[Answered ]-How to customize django admin search results in many to many fields

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

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

Leave a comment