Code

Opened 5 years ago

Closed 3 years ago

#10212 closed (duplicate)

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

Reported by: kyle.fox@… Owned by: nobody
Component: contrib.admin Version: 1.0
Severity: Keywords: ChangeList, admin, ordering, queryset
Cc: Triage Stage: Design decision needed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:

Description

Overriding ModelAdmin.queryset to apply an explicit order_by clause doesn't work. Although it looks like it, the example shown won't order by '-birth_date'

class PersonAdmin(admin.ModelAdmin):
    list_display = ['name', 'birth_date']
    
    def queryset(self, request):
        return Person.objects.order_by('-birth_date')
        
admin.site.register(Person, PersonAdmin)

This patch changes ChangeList.get_ordering to respect any ordering clause that is present on the queryset.

Attachments (2)

10212.diff (1.1 KB) - added by kyle.fox@… 5 years ago.
Patch for #10212 - Allows order_by in ModelAdmin.queryset
admin_ordering.diff (2.0 KB) - added by mzzzzc 5 years ago.
More general patch. Also allows multi-level ordering and ordering given in query_set.extra().

Download all attachments as: .zip

Change History (7)

Changed 5 years ago by kyle.fox@…

Patch for #10212 - Allows order_by in ModelAdmin.queryset

comment:1 Changed 5 years ago by anonymous

  • Component changed from Uncategorized to django.contrib.admin
  • Has patch set
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

comment:2 Changed 5 years ago by jacob

  • Triage Stage changed from Unreviewed to Design decision needed

Is there a reason not to just use ordering on the ModelAdmin?

comment:3 Changed 5 years ago by kyle.fox@…

Yes -- I'm using django-mptt, which has a custom manager to calculates the ordering of objects according to hierarchy.

Currently, if you try to use a custom manager which defines it's own ordering, the admin *drops* that order by clause.

comment:4 Changed 5 years ago by oyvind

I also hit this issue. Would be easier to solve with the patch in #9749.

Changed 5 years ago by mzzzzc

More general patch. Also allows multi-level ordering and ordering given in query_set.extra().

comment:5 Changed 3 years ago by julien

  • Resolution set to duplicate
  • Status changed from new to closed

This is a dupe of #7309.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.