Search code examples
djangodjango-querysetdjango-q

Django Q Objects - Return both True and False matches


I am building a search feature with multiple T/F filter options, like so:

Search: ________________

Filters:
___ Open to Public
___ Parking Available
_x_ Free Entrance

In this case the user is specifically looking for events that are free to get into. I would like my Q object to return keyword matched objects where free_entrance is set to True.

My thought is to define the variables in my search function:

search_public = None
search_parking = None
search_free_entrance = True

and set the Q object up like so:

q_objects.append(
     Q(
        name__icontains=search_term, 
        public__icontains=search_public, 
        parking__icontains=search_parking,
        free_entrance=search_free_entrance
      )
)

However, I want all objects (True or False) to be returned for the unfilitered variables (instead of only objects set to None). Is there a keyword I can insert, or is there a Q object filter type that I am missing?

UPDATE: In addition to the posted answer, *args can also be used for complex (OR) Q objects:

From: http://www.nomadjourney.com/2009/04/dynamic-django-queries-with-kwargs/

args = ( Q( name__icontains = 'search_term' ) | Q( company__icontains = 'search_term' ) )

Solution

  • Use kwargs:

    search = {'name__icontains': search_term}
    if search_public is not None:
        search.update({'public__icontains': search_public})
    if search_parking is not None:
        search.update({'parking__icontains': search_parking})
    if search_free_entrance is not None:
        search.update({'pree_entrance__icontains': search_free_entrance})
    q_objects.append(Q(**search))
    

    or more complicated example (your question from comment):

    search_kwargs = {'name__icontains': search_term}
    search_args = tuple()
    if search_public is not None:
        search_args += (Q(Q(company__icontains=search_public) | Q(other__icontains=search_public)),)
    q_objects.append(Q(*search_args, **search_kwargs))