1

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.

elena
  • 3,740
  • 5
  • 27
  • 38

1 Answers1

4

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))
Johannes
  • 41
  • 3
  • Yes, I actually used the same operation, only I've used "text=searched_term" instead of "name=searched_term". It seems that there's another bug that causes strange results. If the searched_term's length is 1, this filter is just ignored. Will have to dig this deeper. – elena Jan 21 '15 at 14:59