Django: show number of related objects in admin list_display

I would like to show the number of related objects in the django property list_display. for example, we have a category field, and we want to show how many blog posts are posted in this category

I have tried this so far:

admin.py:

from .models import Category class CategoryAdmin(admin.ModelAdmin): def category_post_count(self, obj): return obj.post_set.count category_post_count.short_description = "Posts Count" list_display = ['category', 'category_post_count'] 

models.py:

 class Category(models.Model): category = models.CharField(max_length=25) class Post(models.Model): category = models.ForeignKey(Category, null=True, blank=False) 
+8
python django
source share
1 answer

.count is a function, so you should call it adding brackets () at the end:

 def category_post_count(self, obj): return obj.post_set.count() 
+7
source share

All Articles