Lincoln B's answer was right for me.
At first, I just wanted to comment on his solution, but in fact I decided to solve a slightly different problem. I had an admin class that I wanted to βconfigureβ for my needs, namely the django-taggit . In one of my admin.py applications admin.py I added:
# sort tags by name in admin (count items also possible) from taggit.admin import TagAdmin TagAdmin.ordering = ["name"] # make sortable on item_count: # 1. function for lookup def item_count(obj): """This takes the item_count from object: didn't work as model field.""" return obj.item_count # not needed: obj.taggit_taggeditem_items.count() # 2. property in function - admin field name item_count.admin_order_field = 'item_count' # 3. queryset override, with count annotation from django.db.models import Count TagAdmin.queryset = lambda self, request: super(TagAdmin, self).queryset(request).annotate(item_count=Count('taggit_taggeditem_items')) # 4. add to list display TagAdmin.list_display = ["name", item_count]
What was interesting to me was that I could not just comment on queryset and add "item_count" to list_display - because TagAdmin did not have an item_count method, and not a method or field in the Tag model class (only in queryset ).
Tomasz Gandor May 28 '13 at 9:59 a.m. 2013-05-28 09:59
source share