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
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()