[Django]-Django ORM Number of books per author

4đź‘Ť

âś…

Give related_name to

authors = models.ManyToManyField(Author, related_name='book_auths')

Then

author = Author.objects.get(id=43)
auth_books = author.book_auths.all()

#auth_books are all books which belong to one author

Or

author = Author.objects.get(id=43)  
books = Book.objects.filter(author=author) 

Will give all books where the author is the given one.

Or if you want to know for all authors

authors = Authors.objects.all()
books = Book.objects.filter(author__in=(x for x in authors))

Gives you all books which have authors who exist in db.

To know how many: just attach .count() to result queryset.

👤doniyor

4đź‘Ť

All django objects have a built-in reverse relationship, so you can go “backwards” and “forwards”. This means, that once you have an author, you can do this:

a = Author.objects.get(name='A1 Author')
a.book_set.count()

To get counts for all authors:

for a in Author.objects.all():
   print('Author: {} - Number of Books: {}'.format(a, a.book_set.count()))
👤Burhan Khalid

1đź‘Ť

Heres the simple solution:

Author.objects.annotate(count=Count('book_set'))

And then u can iterate it and call “count” as property. More about “book_set”

👤Mastermind

Leave a comment