Django Admin list_display add column [count records of related ForeignKey]
<p>I am new to Python and Django.</p>

<p>I was trying to count the foreign key items/records of a model and display it as a column in the Admin list_display.</p>

<p>So I have a model "Author", as Foreign key to model "Book".</p>

<p>Here's the models.py:</p>

<pre><code>class Author(models.Model):

    name = models.CharField(
        max_length=100,
    )

    class Meta:
        ordering = ['-name ']
        verbose_name = _('Author')
        verbose_name_plural = _('Authors')

    def __str__(self):
        return self.author

    @models.permalink
    def get_absolute_url(self):
        return reverse('author_detail', kwargs={'pk': self.pk})

class Book(models.Model):
    author = models.ForeignKey(
        'Author',
        related_name='menu_items', 
        verbose_name=_('author'),
    )

    bookname= models.CharField(
        max_length=100,
    )

    publisher= models.CharField(
        max_length=100,
    )
    class Meta:
        ordering = ['-bookname']
        verbose_name = _('Book')
        verbose_name_plural = _('Books')

    def __str__(self):
        return self.bookname

    @models.permalink
    def get_absolute_url(self):
        return ('book_detail', [self.pk])
</code></pre>

<p>Here's the admin.py</p>

<pre><code>from django.contrib import admin
from .models import Author, Book

class BookInline(admin.TabularInline):
    model = Book
    extra = 1

@admin.register(Author)
class LibraryAdmin(admin.ModelAdmin):
    def NumberOfBooks(self, obj):
        #I guess sth is wrong here when trying to count the book_set
        return obj.book_set.count()

    NumberOfBooks.short_description = "Books Count"
    list_display = ['bookname', 'publisher', 'NumberOfBooks']
    inlines = [BookInline]
</code></pre>

<p>I want to count how many books each Author wrote, and display like this on the second level of the admin page <strong><em>Home>Authors>Author</em></strong>:</p>

<pre><code> Author | Books Count
Someone1  NumberOfBooks
Someone2  NumberOfBooks
Someone3  NumberOfBooks
Someone4  NumberOfBooks
</code></pre>

<p>However I get the error:</p>

<pre><code>'Author' object has no attribute 'book_set'
</code></pre>

<p><strong>1. did I do the obj.book_set.count() wrong?</strong>
I thought <code>obj.book_set</code> would refer to "book" under the same "author"(obj), sounds like I misunderstood it but I am not sure how to achieve what I intended to.</p>

<p><strong>2. Instead, if I wanted to add a field to 'Authors' which would auto-count number of "book" related to each Author, should this be a better approach and so how to do it?</strong></p>