Home > front end >  Django count all unique accurance of a many to many field
Django count all unique accurance of a many to many field

Time:06-16

I have models like :

class Book:
    author = models.ManyToManyField()

class Author:
    ...

I want to get all unique authors that have books.

example

BookA: AuthorA, AuthorB
BookB: AuthorB, AuthorC

Auther D, E, F has no book

so the result should be a query set of Author ABC.

Most existing answers are just count of authors of each book. Thanks

CodePudding user response:

You can try this:

Books.objects.values_list('Author').distinct.()

CodePudding user response:

You can annotate the queryset with a Count to get the number of books an Author has, then filter the queryset by the annotated value:

from django.db.models import Count

queryset = Author.objects.annotate(books_count=Count("book_set")).filter(
    books_count__gt=0
)

The approach above is great if you eventually want to change the books_count required. If you're sure you'll always only want to check if the user has any books at all, you can also use book_set__isnull:

queryset = Author.objects.filter(book_set__isnull=False)

CodePudding user response:

@yyyyyyyan answer is perfectly fine. You can also use Exists subquery to do the same and more if you needed more filtering

Author.objects.filter(Exists(Book.object.filter(author=OuterRef('pk')))
  • Related