Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
Django filter by many-to-many field doesn't work

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!