Modifying a Change List
00:14 Since this representation will also show up in drop-downs and multi-selects, you definitely want to make it as easy to understand as possible. You can customize change list pages in far more ways than just modifying an object’s string representation.
list_display attribute of an
admin.ModelAdmin object specifies what columns are shown in the change list. This value is a tuple of attributes of the object being modeled. For example, in
PersonAdmin as follows.
Each attribute is shown in a column on the page. As you can see, the two columns are clickable, allowing you to sort the page by the column data. The admin also respects the
ordering attribute of a
ordering attribute will default all queries on
Person to be ordered by
last_name, and then
first_name. Django will respect this default order for both the admin and when fetching objects.
obj parameter is the object for the row that’s being displayed. In this case, you use it to query the corresponding
Grade objects for the student, with the response averaged out over
If you had such a method, you could add it to the
list_display attribute. The example here shows what you can do in a
ModelAdmin object, but it probably isn’t the best choice for your code. By default, only those columns that are object attributes are sortable.
show_average() isn’t an attribute, so it’s not sortable.
This is because the sorting is performed by an underlying
QuerySet, not on the displayed results. There are ways of sorting these columns in some cases, but that’s beyond the scope of this course.
Unfortunately, Django hasn’t yet added f-string support for
format_html(), so you’re stuck with the
.format() syntax. With those changes made,
show_average() now has a custom title,
"Average Grade", and is formatted to be in bold italics. In the next video, you’ll learn how to link other objects within the admin.
Become a Member to join the conversation.