Suppose I have a Book model containing a foreign key to a Publisher model.
How can I display in the Django admin a column with the number of books published by each publisher, in a way that I can use the built-in sorting?
Suppose I have a Book model containing a foreign key to a Publisher model.
How can I display in the Django admin a column with the number of books published by each publisher, in a way that I can use the built-in sorting?
Try something like this:
You should indeed start off with adding:
But the correct way to add it as a sortable field is:
And then you can just add 'count' to the list_display attribute of model admin in admin.py
Try this:
make a new Manager (and aggregate with count on the book relation field):
sort it on
pubcount
:Lincoln B's answer was the right way for me.
At first I wanted to just comment on his solution, but I actually found myself solving a slightly different problem. I had an admin class, which I wanted to "customize" to my needs - namely the
django-taggit
admin. In one of my application'sadmin.py
, I added:The interesting observation for me was, that I could not just annotate the
queryset
, and add"item_count"
tolist_display
- because there was noitem_count
method inTagAdmin
, nor a method or field in theTag
model class (only in thequeryset
).I had the same issue (I cannot change my model's manager to add slow annotations or joins). A combination of two of the answers here works. @Andre is really close, the Django Admin supports modifying the queryset for just the admin, so apply the same logic here and then user the admin_order_field attribute. You still need to add the new admin field to list_display, of course.