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

Handle reverse many-to-many relation

Open Vayel opened this issue 5 years ago • 2 comments

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 avatar Oct 27 '20 11:10 Vayel

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

Vayel avatar Oct 27 '20 12:10 Vayel

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

jaredahern avatar Mar 01 '21 01:03 jaredahern