Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get filtered queryset in django admin?

Tags:

python

django

I have many different filters in Django admin:

class OrderAdmin(admin.ModelAdmin):
    ...
    list_filter = ('field_1', 'field_2', 'field_3', ... , 'field_N')
    ...

I need to get filtered queryset in my overridden method changelist_view before parent changelist_view is called:

class OrderAdmin(admin.ModelAdmin):
    ...
    def changelist_view(self, request, extra_content=None):
        # here i need filtered queryset and I don`t know 
        # which filters have been applied
        return super().changelist_view(request, extra_context)
    ...

if I calling get_queryset before super in changelist_view it returns queryset without filters.

like image 337
react Avatar asked Apr 07 '16 11:04

react


People also ask

What is Django filter queryset?

Django Filter Queryset Introduction of Django Filter Queryset When the database connectivity is been established in Django, there is always a need of extracting the needed columns alone from the database and their corresponding rows, basically, the filter query set in django model filters is used for achieving this.

How to create custom list filter in Django?

For custom filtering, you can define your own list filter by subclassing django.contrib.admin.SimpleListFilter. You need to provide the title and parameter_name attributes, and override the lookups and queryset methods, e.g.:

What is filter queryset in SQL Server?

When a value is expected to be retrieved from the database then the filter queryset section of the queryset oriented extraction comes into play. Mentioning a filter of a specific column will help us to filter and pull those corresponding values alone from the queryset retrieved.

How do I filter a change list in modeladmin?

ModelAdmin classes can define list filters that appear in the right sidebar of the change list page of the admin, as illustrated in the following screenshot: To activate per-field filtering, set ModelAdmin.list_filter to a list or tuple of elements, where each element is one of the following types: A field name.


1 Answers

New version of Django admin use custom objects for ChangeList view with custom get_queryset method.

As you can see in Django source:

def changelist_view(self, request, extra_context=None):
    ...
    ChangeList = self.get_changelist(request)

    cl = ChangeList(request, self.model, list_display,
        list_display_links, list_filter, self.date_hierarchy,
        search_fields, list_select_related, self.list_per_page,
            self.list_max_show_all, self.list_editable, self)

    # Actions with no confirmation
    if (actions and request.method == 'POST' and
            'index' in request.POST and '_save' not in request.POST):
        if selected:
            response = self.response_action(request, queryset=cl.get_queryset(request))
    ...

You must override self.get_changelist(request) and return your custom ChangeList with overridden get_queryset.

ModelAdmin.get_changelist:

def get_changelist(self, request, **kwargs):
    """
    Returns the ChangeList class for use on the changelist page.
    """
    return MyChangeList  # PUT YOU OWERRIDEN CHANGE LIST HERE

MyChangeList:

from django.contrib.admin.views.main import ChangeList

class MyChangeList(ChangeList):
    def get_queryset(...):
        # if you want change get_queryset logic or add new filters
        ...
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # if you want add some context variable which can be accessed by 
        # {{ cl.some_context_varibale }} variable
        self.some_context_varibale = self.queryset.aggregate(Avg('price'))['price__avg']
like image 193
pahaz Avatar answered Oct 07 '22 16:10

pahaz