Search code examples
pythondjangojoinqueryingdjango-q

How to join multiple params dynamically for django Q object


I'm trying to implement a search in a django sqlite db.

I get a list of unknown length of params which should all be matched with a 'LIKE'. This means I want all objects that match at least one of the params.

As I can see from the django docs I can reach this by using the Q object.

Example:

Students.objects.get(
    Q(name_contains='franz') | 
    Q(birthdate_date=date(2005, 5, 2) | 
    Q(param3_contains='lorem'
)

Now my question is, how can I handle it to join all the Q objects created from params to pass as arguments to the objects.get(). I could not find any on this.

Another issue here is to handle several different Field Lookup types.

I appreciate any advice, help or helping links you can give. Thank you.


Solution

  • If you want to dynamically build the list of queries, you could have a sequence like this:

    request = Q(name_contains='franz')
    
    if condition1:
      request |= Q(birthdate_date=date(2005, 5, 2))
    
    if condition2:
      request |= Q(param3_contains='lorem')
    

    Then:

    Students.objects.get(request)
    

    If you need something even more generic, you could have a function that passes a dict, like:

    conditions = {'name_contains': 'franz',
                  'birthdate_date': date(2005, 5, 2),
                  'param3_contains': 'lorem'}
    

    And build the condition like this (Untested):

    request = None
    for key, value in conditions.items():
      new_request = Q(**{key: value})
    
      if request: request |= new_request
      else: request = new_request