Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

python - In Django Admin, can you limit the filter options, based on the search results?

I have a Django application that has the following example models:

class Artist(models.Model):
    name = models.CharField(max_length=200)


class Album(models.Model):
    name = models.CharField(max_length=200)
    ...
    num_stars = models.IntegerField()
    artist = models.ForeignKey(Artist, on_delete=models.CASCADE)

I have a Album_Admin(admin.ModelAdmin) where I want to combine searching and filtering. I am writing a custom filter using admin.SimpleListFilter on the num_stars field.

I want my filter choices for num_stars to reflect the possible choices in the search results. I don't want to see all the available filter choices that exist in the table, just the ones that exist in the search results.

I tried to store the value from the search field (search_term) in a global variable and than use the variable in the filter, but Changelist view first makes filtering, then it gives the filtered queryset from the search function.

Any suggestion how to achieve this ?

Example: enter image description here

The example in the image above shows the desired solution. After I search by artist_id = 1 in search bar, I want to see only the filter options that are set for albums with artist_id = 1 (** and ****)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes you can. The request is available in the filter class.

For example, I just searched for my name in admin which gives me the following URL;

/admin/authentication/user/?q=mark

Therefore your filter class can get the query from the request;


class FilterQuery(admin.SimpleListFilter):
    """
    List filter to filter alongside the search query
    """
    title = 'search query filter'

    def __init__(self, request, params, model, model_admin):
        super().__init__(request, params, model, model_admin)
        self.search_query = request.GET.get('q')

    def queryset(self, request, queryset):
        """
        Perform the filtering (if required)
        """

        return queryset.filter(name__icontains=self.search_query)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...