Django ModelAdmin override not working

I am trying to override the queryset () of the ModelAdmin class so that the list of objects shown in the admin is sorted into two levels .

I tried the following code, but it does not work, i.e. 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 cannot use ordering = ('category','market') since django states that only the first element in the ordering tuple takes effect (see the note in the documentation here )

+4
source share
3 answers

release notes for Django 1.4 say that Django now supports Multiple sort in admin interface :

Changelog admin now supports multi-column sorting. This respects all elements of the ordering attribute and sorts by several columns by clicking on the headers, designed to simulate the behavior of graphical desktop interfaces.

And from Order ModelAdmin :

Set ordering to specify how object lists should be ordered in Django Admin Views. It must be a list or tuple in the same format as an ordering model parameter. [...] Django rewards all items in a list / tuple; to 1.4, only the first was respected.

In a semi-dependent note - if you override queryset to provide a custom sort order, it seems that Changelist override this sort order. It applies any sort found in the ordering parameter, and if it is not there, it applies the default sort on pk , thereby negating any sort that you did in queryset .

I think it should work - at least this Django Ticket is fixed. But I was just trying to apply a custom view using queryset few days ago, and this did not work for me. Even single-field sorting seemed to be redefined in the final representation. So I did something wrong, or that's not all that was fixed. :)

Note that you can do custom sorting by code, but you must subclass the Changelist and override its get_query_set() method, according to this snippet . (Although this is too much if you only need to sort multiple fields, as Django 1.4 now supports multiple fields).

+1
source

get_queryset works in Django 1.8.

+7
source

I had this problem. Here is what I did:

I subclassed ChangeList and redefined ChangeList.get_query_set to repeat the correct order_by that was previously changed to ChangeList.get_ordering :

This is what I did in my case (I use django-easytree, but the same goes 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:

+3
source

Source: https://habr.com/ru/post/1337848/


All Articles