A.J.
A.J.

Reputation: 9025

manipulating Q objects, Adding new condition dynamically

I have a Q object like this.

params = Q(salt_spray__iregex=keyword) | Q(special_function__iregex=keyword) | Q(comment__iregex=keyword)

Here When I filter my model on the basis of this, things work fine.

Model.objects.filter(params)

But I want to do the following.

params = Q(salt_spray__iregex=keyword) | Q(special_function__iregex=keyword) | Q(comment__iregex=keyword)
if data.get('market'):
    params[project__market] = data['market'] # not sure about this step. 
Model.objects.filter(params)

Code after Solution

data = self.cleaned_data

keyword = data['keyword']
params = Q()
if keyword:
    params |= Q(salt_spray__iregex=keyword) | Q(special_function__iregex=keyword) | Q(comment__iregex=keyword) # Note OR Operator. 

if data['market']:
    params &= Q(project__market=data['market']) # Note here AND Operator 
innovations = Innovation.objects.filter(params)
return innovations

Upvotes: 0

Views: 181

Answers (2)

Maciej Gol
Maciej Gol

Reputation: 15864

You need to or the Q objects with the | operator:

params = Q(salt_spray__iregex=keyword) | Q(special_function__iregex=keyword) | Q(comment__iregex=keyword)
if data.get('market'):
    params |= Q(project__market=data['market'])
Model.objects.filter(params)

Or use operator.or_ as @rinti has mentioned.

Upvotes: 1

rinti
rinti

Reputation: 1273

import operator then you can do it like this:

params = []

# Add as much as you like to your list dynamically
params.append(Q(something))

Model.objects.filter(reduce(operator.or_, params))

Upvotes: 0

Related Questions