how generate complex AND query using Q() in django
queries = request.POST.get('query', '')
print "quires -->", queries
if queries:
queries = json.loads(queries)
print "json queries -->", queries
q = Q()
for field, condition, query in queries:
print "field -->", field
print "condition -->", condition
print "query -->", query
q = q & Q(**{str(field)+"__"+str(condition):query})
print "query output -->", q
book = Book.objects.filter(q & Q(library=library_id)).order_by(*s)
output:
-------
quires --> [["author","icontains","saju"],["editor","startswith","a"]]
json queries --> [[u'author', u'icontains', u'saju'], [u'editor', u'startswith', u'a']]
field -->author
condition-->icontains
query -->saju
field -->editor
condition-->startswith
query -->a
query output --> (AND: ('author__icontains', u'saju'), ('editor__startswith', u'a'))
-----------------
** --> Means keyword argument
* --> Means positional argument
Q() --> can accept keyword argument
order_by() --> can accept positional argument
Q(**{str(field)+"__"+str(condition):query})
order_by(*s)
-----------------
for field, condition, query in queries:
Q(**{str(field)+"__"+str(condition):query})
is equivalent to
Q(**{'author__icontains':'saju', 'editor__startswith':'a'})
that is Q() with keyword arguments
-----------------
No comments:
Post a Comment