Advertisement
Davitkova

get_authors_by_books_count

Mar 29th, 2025
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.53 KB | None | 0 0
  1. def get_authors_by_books_count():
  2.  
  3.     authors = Author.objects.prefetch_related('book_author', 'book_co_authors')\
  4.         .annotate(
  5.             books_count=Count('book_author'),
  6.             co_books_count=Count('book_co_authors'),
  7.             books_total_count=F('books_count') + F('co_books_count')
  8.         ).order_by('-books_total_count', 'name')[:3]
  9.  
  10.     if not authors or authors[0].books_total_count == 0:
  11.         return "No results."
  12.  
  13.     return "\n".join(f"{a.name} authored {a.books_total_count} books." for a in authors)
  14.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement