Home > Software engineering >  Django model filter with `exact` IN operator
Django model filter with `exact` IN operator

Time:11-16

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.

CodePudding user response:

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)
  • Related