Dynamically Constructed Q Filters in Django

In Django, the Q() can be used to construct complex queries, such as OR-ing fields. The docs are pretty straight forward. But what if you want to dynamically choose which fields to OR together? Here is one way:

from django.db.models import Q
from models import MyModel

# Suppose this list is generated dynamically.
model_fields = ['f1', 'f2', 'f3']

# Find all instances where any of these model_fields are not null
query = Q()
for f in model_fields:
    query |= Q(**{'{}__isnull'.format(f): False})

instances = MyModel.objects.filter(query)

This code was inspired by this post on Stackoverflow.

Advertisements

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