我有一个以q
表单命名的搜索字段。当我搜索成员时,我希望它像下面那样过滤
results = Member.objects.filter(Q(mid=q) | Q(mobile=q)).order_by('pub_date')
在其他形式中,我想做类似的事情。
如 :
Account.objects.filter(Q(name=q)|Q(card=q)).order_by('pub_date')
我需要exactly equal filter
,所以使用django-haystack
是多余的。
简单的基本形式:
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
但我不知道如何构造这样的 Q() 语句。