Opened 10 months ago

Last modified 7 weeks ago

#27810 assigned New feature

Add query expression support for ModelAdmin list_display's admin_order_field

Reported by: Andreas Pelme Owned by: Andreas Pelme
Component: contrib.admin Version: master
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


Query expressions cannot currently be used with admin_order_field in a callable on list_display. The code expects a string and crashes when an query expression object is passed instead. This example shows the problem:

def full_name(obj):
    return f'{obj.first_name} {obj.last_name}'
my_callable.admin_order_field = Concat(F('first_name'), F('last_name'))

... which leads to a crash like this:

    self.queryset = self.get_queryset(request)
  File "/Users/andreas/code/django/django/contrib/admin/views/", line 346, in get_queryset
    ordering = self.get_ordering(request, qs)
  File "/Users/andreas/code/django/django/contrib/admin/views/", line 260, in get_ordering
    if order_field.startswith('-') and pfx == "-":
AttributeError: 'CombinedExpression' object has no attribute 'startswith'

It would make sense to be able to make use of all the nice stuff that has gone into query expression from the admin in this case! :)

Change History (4)

comment:1 Changed 10 months ago by Andreas Pelme

Owner: changed from nobody to Andreas Pelme
Status: newassigned

comment:2 Changed 10 months ago by Tim Graham

Summary: ModelAdmin list_display callable does not support query expressions in admin_order_fieldAdd query expression support for ModelAdmin list_display's admin_order_field
Triage Stage: UnreviewedAccepted

comment:3 Changed 10 months ago by Tim Graham

Has patch: set

comment:4 Changed 7 weeks ago by Simon Wiles

any chance of this getting committed? it would be very useful to have...

(specific use-case that drove me here: sorting in admin on a DateField that has NULLs...)

Note: See TracTickets for help on using tickets.
Back to Top