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

154
Views
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 answers
Answer question

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 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!