[Django]-How to join multiple params dynamically for django Q object

12👍

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

1👍

I have a similar requirement in my application. I have to search for a searchterm in all kinds of names:

Qterm = Q(firstname__icontains=searchterm) | \
        Q(lastname__icontains=searchterm) | \
        Q(resume__icontains=searchterm) | \
        Q(companyname__icontains=searchterm))

or, if you want to match one field to a number of searchterms:

Qterm = Q()
for term in ["robot", "animatronic", "automaton"]:
    Qterm |= Q(rolename_icontains=term)

fieldname_icontains ultimately becomes a LIKE. There are also more criteria, like that the user should be ‘active’, which is a boolean field:

Qactive = Q(active=True)

At the end, I combine all these Q objects like this:

Qs = Qterm & Qactive & Qthis & Qthat 

…and I retrieve my active users like this:

userlst = Users.objects.filter(Qs)

I hope this helps!

Leave a comment