2

There is a model of Article and it has many-to-many categories field. I want to filter it by that field but it doesn't work as i expected. For example:

MyModel.objects.filter(categories__id__in = [0, 1, 2])

it gets model with categories 0 and 1 even if it hasn't category with id 2. i tried something like this:

MyModel.objects.filter(Q(categories__id = 0) & Q(categories__id = 1) & Q(categories__id = 2))

but it even doesn't work. it doesn't even gets model if it has all of this categories.

By the way, i don't want to use more than 1 filter method

So, is there any solution for me?

Thanks.

P.S: django AND on Q not working for many to many - the same question but author still doesn't get an answer.

greg
  • 63
  • 4

1 Answers1

1

You can count if it matches three Categorys and thus only retrieve items where the three match:

from django.db.models import Count

MyModel.objects.filter(
    categories__id__in=[0, 1, 2]
).annotate(
    category_count=Count('categories')
).filter(category_count=3)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555