Django model filter with "exact" IN operator

Question:

I want to find all users who have exactly same tags like a particular category (exactly same tags and also same amount of tags assigned)

Something like…

category = Category.objects.first()
User.objects.filter(tags__in=category.tags.filter())

But this returns also users who share even only one tag with the category.

Models are

class User(models.Model):
    tags = models.ManyToManyField(Tag, blank=True, related_name='users')


class Category(models.Model):
    tags = models.ManyToManyField(Tag, blank=True, related_name='categories')

class Tag(models.Model):
    name = models.CharField(max_length=255, blank=False)

Any solution appreciated.

Asked By: Volt

||

Answers:

Not the best solution, but will work probably.

Iterate over User queryset and filter them one by one. example:

category = Category.objects.first()
for tag in category.tags.all():
    qs = User.objects.filter(tags__id=tag.id)

Other one:

category = Category.objects.first()
tag_ids = category.tags.values_list("id", flat=True)

valid_users = []
for user in User.objects.all():
    user_tag_ids = user.tags.values_list("id", flat=True)
    if set(user_tag_ids) == set(tag_ids):
        valid_users.append(user)
Answered By: Bartosz Stasiak
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.