Grouping only by Manytomany’s first item in Django

Asked

Viewed 62 times

0

I have two tables: Author and Book

where Book has an Author = ManyToManyField

Note the examples with A1 (author one) and L1 (book one), so on.

Author - Book
A1 - L1, L2, L3
A2 - L1
A1 - L3
A1 - L1
A1 - L1
A2 - L2, L3
A1 - L3

I need to do a grouping by taking only the first book from M2M. And return the following count:

Books
L1 = 4
L2 = 1
L3 = 2

Total: 7

I tried to

Author.objects.values('book').annotate(quant=Count('book')).order_by('book').values('book', 'quant')

But it returns me a greater amount of books, since it counts all books of the M2M relation.

How do I pick up only one book of each iteration, to return the desired result?

1 answer

0


Solved.

def books_list(self):
    count = {}
    for item in Author.objects.all():
        first_book = item.books.first()
        if first_book:
            count[first_book] = count.get(first_book, 0) + 1
    return count

Browser other questions tagged

You are not signed in. Login or sign up in order to post.