I’ve been stuck on this and looked around and found some fascinating & clever solutions, but the other day I realized how simple this really need be.
The problem: You have an undetermined number of constraints you may want to filter your database query by, and the Q object appears to require the programmer to have a pretty rigid query.
At least that was the misconception I started with.
The solution involves noting that the | operator is really just returning another Q object, which implies that you should be able to store that Q object and “or” some more Q objects onto later, just as easily as you could do inline.
Take this example:
myUsers = userInfo.objects.filter(Q(user=selectedUser) | Q(user=selectedUser) | Q(user=selectedUser))
This example assumes we have a list of selectedUsers that we need more information about. But in the real world, you probably won’t know how long that list of selectedUsers really is.
So instead we can do something like the following:
usersQ = Q() for sU in selectedUsers: usersQ = usersQ | (userid=sU)
And then you can go ahead and add usersQ to a chained filter on your query, and you will get the results you want. No fancy stuff.