Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda