[Answer]-Django ManytoMany retireving all objects that fulfill a condition simoultaneously

1👍

You use the double-underscore syntax, as described further down that page.

Entry.objects.filter(authors__name__startswith='R')

Edit

So what you actually want to do is to exclude all those authors who do not start with R. You could do that with a Q object and the ~ operator:

from django.db.models import Q
Entry.objects.exclude(~Q(authors__name__startswith='R'))

0👍

I can think of a one tricky solution for such a task. (not tested)

Entry.objects \
    .annotate(num_authors=Count('authors')) \
    .filter(authors__name__startswith='R')
    .annotate(num_authors_with_r=Count('authors')) \
    .filter(num_authors=F('num_authors_with_r'))

What’s the idea?

  1. We get the count of all authors.
  2. Do filter
  3. Return only rows with filtered authors count == all authors count
👤Todor

Leave a comment