Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda