farhan0581 / django-admin-autocomplete-filter

A simple Django app to render list filters in django admin using autocomplete widget.
GNU General Public License v3.0
351 stars 75 forks source link

Doesn't work with reverse m2m or m2o relations #73

Open KaratasFurkan opened 2 years ago

KaratasFurkan commented 2 years ago
# Models

class Student:
    name = models.CharField()

class Course:
    students = models.ManyToManyField(Student, related_name='courses')

# Admins

class StudentAdmin:
    list_filter = (AutocompleteFilterFactory('courses', 'courses'),)

Gives this error:

AttributeError: 'ManyToManyRel' object has no attribute 'get_limit_choices_to'

Might be related to #53

KessoumML commented 2 years ago

Any workaround for reverse m2m or m2o relations ?

KaratasFurkan commented 2 years ago

@KessoumML here is what I use, it is pretty hacky but it's work:

# Models

class Student:
    name = models.CharField()

class Course:
    students = models.ManyToManyField(Student, related_name='courses')

class Book:
    course = models.ForeignKey(Course)

#---------------------------------------------------------------------
# Admins

from admin_auto_filters.filters import AutocompleteFilter

# Hacky filter
class CourseFilter(AutocompleteFilter):
    title = 'course'  # Filter Title
    rel_model = Book  # A random model with Course foreignkey, doesn't need to be related to Student. Just used to get right relation object instead of "ManyToManyRel object".
    field_name = 'course'  # Book.<field_name> --> Book.course
    parameter_name = 'courses'  # Student.<parameter_name> --> Student.courses

class StudentAdmin:
    list_filter = (CourseFilter,)
KessoumML commented 2 years ago

@KaratasFurkan thanks for you suggestion, already solved my issue in #76 The problem was introduced after updating to Django 3.2 which is released with a minor feature that breaked the autocomplete.

ModelAdmin.autocomplete_fields now respects ForeignKey.to_field and ForeignKey.limit_choices_to when searching a related model.