Dynamic query filters for django

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[0]) | Q(user=selectedUser[1]) | Q(user=selectedUser[2]))

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.


About andyortlieb

I've been a tinkerer and a lazy ideologist since I gained my first personal computer in 1989. I have an aversion to formal education and I prefer to learn things by experimentation. That is not a brag, it has not been a particularly helpful set of traits. My primary goals are to increase my safety, pleasure and usefulness as I work to build and modify technologies that will bring those same attributes to the masses irrespective of government. This is the documentation of my attempt at that journey.
This entry was posted in Computer, Programming, Software, Uncategorized and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s