Opened 4 weeks ago

Closed 3 weeks ago

#37233 closed Bug (fixed)

Admin renders a sort control for every "__str__" column

Reported by: blighj Owned by: Akshat Sparsh
Component: contrib.admin Version: 5.1
Severity: Normal Keywords:
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Since ticket:10743#comment:26, any __str__ column in an admin list view is rendered as a sortable column, regardless of whether it has been linked to a column and marked as sortable.
This simple model would reproduce it.

# models.py
class SortingTest(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name


# admin.py
admin.site.register(SortingTest)

list_display defaults to ("__str__",) but no sorting has been configured for the model's __str__, so the column should not be sortable.

result_headers() in django/contrib/admin/templatetags/admin_list.py
decides sortability with a substring test:

if not admin_order_field and LOOKUP_SEP not in field_name:
    is_field_sortable = False

LOOKUP_SEP is "__" an so __str__ flags as sortable

ChangeList.get_ordering_field() resolves the same name by attribute lookup
rather than by checking for double underscores, correctly finds no admin_order_field, and
get_ordering() drops it:

order_field = self.get_ordering_field(field_name)
if not order_field:
    continue

Potentially result_headers could use get_ordering_field or some other technique.

This showed up reviewing ticket:27752#comment:16, which has the bigger issue that sorting on __str__ doesn't work anyway. I don't judge this as a huge issue as once you need sorting you are most likely using specific list_dispaly values.

Change History (8)

comment:1 by Sarah Boyce, 3 weeks ago

Triage Stage: UnreviewedAccepted

Well spotted! Thank you

comment:2 by Akshat Sparsh, 3 weeks ago

Owner: set to Akshat Sparsh
Status: newassigned

comment:3 by Akshat Sparsh, 3 weeks ago

Has patch: set

comment:4 by Akshat Sparsh, 3 weeks ago

Replacement PR: PR

comment:5 by blighj, 3 weeks ago

Patch needs improvement: set

comment:6 by Akshat Sparsh, 3 weeks ago

Patch needs improvement: unset

comment:7 by blighj, 3 weeks ago

Triage Stage: AcceptedReady for checkin

comment:8 by Sarah Boyce <42296566+sarahboyce@…>, 3 weeks ago

Resolution: fixed
Status: assignedclosed

In 92e1d9e:

Fixed #37233 -- Prevented sort controls for unordered str admin columns.

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