[Django]-How to build complex django query as a string

4👍

Construct a Q object and use it in filter():

from viewer.models import Model1
from django.db.models import Q

list1 = [
    {'nut' : 'peanut', 'jam' : 'blueberry'},
    {'nut' : 'almond', 'jam' : 'strawberry'}
]

q = Q()
for x in list1:
    q.add(Q(**x), Q.OR)

query_results = Model1.objects.filter(q)

Or, you can use operator.or_ to join the list of Q objects:

import operator
from viewer.models import Model1
from django.db.models import Q

list1 = [
    {'nut' : 'peanut', 'jam' : 'blueberry'},
    {'nut' : 'almond', 'jam' : 'strawberry'}
]

query_results = Model1.objects.filter(reduce(operator.or_, 
                                             [Q(**x) for x in list1]))
👤alecxe

Leave a comment