Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ModelAdmin queryset override doesn't work

I'm trying to override the queryset() of a ModelAdmin class so that the list of objects shown in admin would be sorted by two levels.

I've tried the following code, but it does not work, i.e. the table is not sorted as expected

class ProductAdmin(admin.ModelAdmin):
    def queryset(self, request):
        qs = super(ProductAdmin, self).queryset(request)
        return qs.order_by('category','market')

    list_display = ('category', 'market', 'name', 'quantity')

admin.site.register(Product, ProductAdmin)

btw, you can't use ordering = ('category','market') as django specifically states that only the first item in the ordering tuple takes effect (see note in the documentation here)

like image 807
Jonathan Livni Avatar asked Dec 16 '22 17:12

Jonathan Livni


2 Answers

get_queryset works in Django 1.8.

like image 181
radeklos Avatar answered Mar 20 '23 17:03

radeklos


I had this exactly problem. Here's what I did:

I subclassed ChangeList and overrode ChangeList.get_query_set to redo the correct order_by that was previously changed by ChangeList.get_ordering:

This is what I did in my case (I'm using django-easytree, but the same applies for django-mptt):

class MyChangeList(ChangeList):

    def get_query_set(self):
        qs = super(MyChangeList, self).get_query_set()

        return qs.order_by('tree_id', 'lft')

Also, check these tickets:

  • "NFA: Don't override order_by if no default ordering is specified"

  • "Admin ChangeList doesn't apply 'order_by' clause specified by ModelAdmin.queryset"

like image 43
Tiago Avatar answered Mar 20 '23 17:03

Tiago