[Python] Django: show the count of related objects in admin list_display

Discussão em 'Python' iniciado por Stack, Maio 5, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to show the count of related objects in django's list_display property. 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)

    Continue reading...

Compartilhe esta Página