Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 606
Igle Avatar asked Jun 01 '26 13:06

Igle


1 Answers

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
like image 197
Dric512 Avatar answered Jun 04 '26 03:06

Dric512



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!