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

Handle reverse many-to-many relation #47

Open Vayel opened 3 years ago

Vayel commented 3 years ago

Hi!

Thanks for this great package! Here is an enhancement proposal: being able to filter by a reverse many-to-many relation. For instance:

class Publication(models.Model):
    title = models.CharField(max_length=30)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication)

# Filter publications by articles they belong to
# Raises `django.core.exceptions.FieldDoesNotExist: Publication has no field named 'article_set'`
class ArticleFilter(AutocompleteFilter):
    title = "Article"
    field_name = "article_set"

class PublicationAdmin(admin.ModelAdmin):
    model = Publication
    list_filter = (ArticleFilter,)

Thanks!

Vayel commented 3 years ago

Defining the related_name seems to fix the error:

class Publication(models.Model):
    title = models.CharField(max_length=30)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication, related_name="articles")

# Filter publications by articles they belong to
class ArticleFilter(AutocompleteFilter):
    title = "Article"
    field_name = "articles"  # Use the related name here

class PublicationAdmin(admin.ModelAdmin):
    model = Publication
    list_filter = (ArticleFilter,)
jaredahern commented 3 years ago

I think this should all be fixed by the changes in pre_release now.