I have a search field named q
in a form.When I am searching a member, I want it filter like below
results = Member.objects.filter(Q(mid=q) | Q(mobile=q)).order_by('pub_date')
In other forms I want to do something similar.
such as :
Account.objects.filter(Q(name=q)|Q(card=q)).order_by('pub_date')
I need exactly equal filter
, so using django-haystack
is overkill.
Simple base form:
class SimpleSearchForm(forms.Form):
q = forms.CharField(required=False)
search_fields = []
def __init__(self, model=None):
super(SimpleSearchForm, self).__init__()
if not model:
raise Exception('SimpleSearchForm need init with a model')
self.model = model
def search(self):
q = self.cleaned_data['q']
if len(self.search_fields) > 0:
# construct a Q() statement, filter result and return
But I don't know how to construct such a Q() statement.