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)
get_queryset
works in Django 1.8.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With