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

150
Vistas
Filtering tags in M2M Field Django

So I have my models

Class Category((models.Model)
    category = models.CharField()

class Group(models.Model)
    Title = models.CharField()
    category = models.ManyToManyField(Category, related_name= tags)

So I want to be able to filter all the groups with similar tags to the group currently in view

In my views.py I tried

group = Group.objects.get(id=pk)
groups = Group.objects.filter(category=group.category)

But that doesn't work

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can retrieve all the groups that have at least one Category in common with:

Group.objects.filter(category__in=group.category.all()).distinct()

The .distinct() call [Django-doc] prevents listing a Group that many times as there are matching categorys.

Another option is to use the relation in reverse, and thus work with:

Group.objects.filter(category__tags=group).distinct()

The related name however does not make much sense: the related_name=… parameter [Django-doc] is the name of the relation in reverse, related_name='groups' thus makes more sense. In that case we query with:

Group.objects.filter(category__groups=group).distinct()
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