Search code examples
pythondjangodjango-ormdjango-q

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

Solution

  • 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.