django-admin-autocomplete-filter
django-admin-autocomplete-filter copied to clipboard
Handle reverse many-to-many relation
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!
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,)
I think this should all be fixed by the changes in pre_release now.