[Answer]-Manipulating Q objects, Adding new condition dynamically

1👍

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.

0👍

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))
👤rinti

Leave a comment