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

[Help] Filter by foreign key of foreign key #67

Open 1oglop1 opened 3 years ago

1oglop1 commented 3 years ago

Hi, I'm new to Django so there are many things that are not obvious to me.

I extended example models like this:

from django.db import models

class Publisher(models.Model):
    name = models.CharField(max_length=10)

class Artist(models.Model):
    name = models.CharField(max_length=128)
    publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE, null=True, blank=True)

class Album(models.Model):
    name = models.CharField(max_length=64)
    artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
    cover = models.CharField(max_length=256, null=True, default=None)

And I'd like to be able to filter by Publisher on AlbumAdmin page. How can I do that?

I know how to display the Publisher.name but I cannot figure out how to use the filter.

@admin.register(Album)
class AlbumAdmin(admin.ModelAdmin):
    list_filter = [ArtistFilter, PublisherFilter]
    list_display = ["name", "artist_name", "publisher_name"]

    @admin.display(description="Artist Name")
    def artist_name(self, obj):
        return obj.artist.name

    @admin.display(description="publisher name")
    def publisher_name(self, obj):
        try:
            return obj.artist.publisher.name
        except AttributeError:
            return ""

My hunch is that I need to use the custom view but whatever I tried from the examples finished with 2 errors: One mentioned in #60 and the second one AttributeError: 'DeferredAttribute' object has no attribute 'queryset'

Thank you for your help!

EDIT 1 I found this project: https://github.com/thomst/django-more-admin-filters and they seem to be using reverse_field_path method which seem to be more intuitive.

RomikimoR commented 2 years ago

Hello @1oglop1, Did you manage to fix this error ?

lgajpi commented 2 years ago

redefine the class with admin register - it helped me. Example: @admin.register(models.YOUMODEL) class YOUMODELAdmin(admin.ModelAdmin): list_display = ( "FILED", ) search_fields = ("FILED",) And add this into u filter_list: AutocompleteFilterFactory( title="YOUR_TITLE", base_parameter_name="ENTITYENTITYENTITY", ),