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 often find myself figuring out some niche oddities, only to find myself stuck on those same problems a year later due to my wide yet thin activity in certain topics related to my career and hobbies. This blog is where I document these nuances (or nuisances) to ease my pain the second time around, and hopefully that of some other fellow desperate internet scouts.
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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s