1
ok, so if I am getting you right, you are ultimately asking ‘how to construct such a Q() statement’.
For making dynamic Q() statements, you may use powerful **kwargs feature.
For dynamically making your following query:
results = Member.objects.filter(Q(mid=q) | Q(mobile=q))
Here is the code:
from django.db.models import Q
import operator
predicates = [('mid', q), ('mobile', q)] # You may form this list dynamically as per your requirement
q_list = [Q(x) for x in predicates] # generates a list of Q objects dynamically
results = Member.objects.filter(reduce(operator.or_, q_list)) # to combine all Q objects, reduce and operator python methods are used
In this way, you may make dynamic queries
For more detailed description, visit here
Source:stackexchange.com