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
- [Django]-Django-haystack elasticsearch as backend and searchengine
- [Django]-Overriding Django Admin's main page? – Django
- [Django]-Set image size limit and resize image if is needed
- [Django]-Django set multiple allowed hosts
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
- [Django]-Use values() in Django query to get Model instead of ID
- [Django]-How to avoid repeated values retrieved from database?
- [Django]-Stop django from automatically unicodifing POST stuff
- [Django]-Boto3 deprecation warning on import
- [Django]-Adding days to a date via the ORM
Source:stackexchange.com