django-admin-autocomplete-filter icon indicating copy to clipboard operation
django-admin-autocomplete-filter copied to clipboard

Doesn't work with reverse m2m or m2o relations

Open KaratasFurkan opened this issue 2 years ago • 3 comments

# 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

KaratasFurkan avatar Nov 17 '21 12:11 KaratasFurkan

Any workaround for reverse m2m or m2o relations ?

KessoumML avatar Feb 24 '22 10:02 KessoumML

@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,)

KaratasFurkan avatar Feb 25 '22 06:02 KaratasFurkan

@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.

KessoumML avatar Feb 25 '22 11:02 KessoumML