Django: show the count of related objects in admin list_display

Although the accepted answer will produce the expected result, this is not how it should be done in most cases because it will generate a "n+1" problem, a.k.a one more sql query per row.

You should modify your admin class (or manager if you need it in more situations than just the admin) to retrieve a count annotation (which is django's term for aggregate columns) and then use this value. It will compute the count in the main select query, avoiding generation of non necessary queries.

...
from django.db.models import Count
...

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = [..., 'post_count']

    ...

    def post_count(self, obj):
        return obj.post_count

    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        queryset = queryset.annotate(post_count=Count("post"))
        return queryset


.count is a function so you have to call it by appending parentheses () at the end:

def category_post_count(self, obj):
    return obj.post_set.count()

Tags:

Python

Django