Grouping only the first item in ManyToMany in Django

0

I have two tables: Author and Book

where Book has an author = ManyToManyField

Look at the examples with A1 (author one) and L1 (book one), and 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 just taking the first M2M book. And return the following count:

Books
L1 = 4
L2 = 1
L3 = 2

Total: 7

I've tried

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

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

How do I get just one book from each iteration, to return the desired result?

    
asked by anonymous 19.07.2016 / 16:51

1 answer

0

Resolved.

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
    
14.09.2016 / 21:44