0

I have a checkbox with multiple values. For example, hobbies. When the user choose some hobbies, he wants to see the person who has all those hobbies.

I dont go into details for sake of clarity so here's how I read all the checked values and put them in my "big" query, which is, as you may guess: q:

hobbies2 = [int(l) for l in g.getlist('hobbies2')]
if len(hobbies2):
    q = q & Q(personne__hobbies2__in=hobbies2)

The problem is that it returns all persons who have a hobby in common (i.e. it's like "or", not "and").

How to get all those many to many values with a and?

1 Answer 1

1

The __in operator is for filtering by a set. It is not meant for checking multiple values at once in a many-to-many relationship.

It literally translate to the following in SQL:

SELECT ... WHERE hobbies IN (1, 3, 4);

So you'd need to build your query using AND conditions. You can do this with consecutive filters:

queryset = Personne.objects.all()

# build up the queryset with multiple filters
for hobby in hobbies2:
    queryset = queryset.filter(hobbies2=hobby)
Sign up to request clarification or add additional context in comments.

3 Comments

Are you sure that personne__hobbies2=hobby will not eliminate people when there's more than one hobby? For example: kayak = 1, ski = 2. This will filter first personne__hobbies2=1 then after personne__hobbies2=1. Are you sure that it may work?
With consecutive Q objects doesnt work. I've tried the #1 solution here: stackoverflow.com/questions/8618068/… it doesnt work too.
Thanks for the link, I've updated my answer to remove the Q queries. However, the consecutive filters should work since those are demonstrated in the link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.