elena
elena

Reputation: 4178

Intersection of two SearchQuerySets in Django

So I have a similar model:

class Whatever(SlugMixin, models.Model):
    user = models.ForeignKey(auth_models.User, related_name='user+', verbose_name=_('User'), on_delete=models.PROTECT)
    name = models.CharField(verbose_name=_('Name'), max_length=200)

I am trying to find all objects that belong to that user and that have a name which matches the searched term.

I have already understood that doing:

SearchQuerySet().filter(text=searched_term).filter(user=user)

won't work. It returns to me the union of those two. However, I want the intersection of those two conditions, and not the union. I understand that this happens because the user and text belong to different models.

Upvotes: 1

Views: 195

Answers (1)

Johannes
Johannes

Reputation: 41

Just to make sure we are on the same page what unions and intersections mean, let's take a short example:

Group A = [1, 2, 3]

Group B = [2, 3, 4, 5]

Intersection of A and B would be [2, 3]

and union of A and B would be [1, 2, 3, 4, 5]

If you are looking for intersection:

desired_queryset = Whatever.objects.filter(user=user, name=searched_term)

If you are looking for union:

from django.db.models import Q
desired_queryset = Whatever.objects.filter(Q(user=user) | Q(name=searched_term))

Upvotes: 4

Related Questions