我在数据库中有一个名为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()语句。你知道吗
好吧,如果我说对了,你最终会问“如何构造这样一个Q()语句”。你知道吗
为了生成动态Q()语句,可以使用强大的**kwargs特性。 动态进行以下查询:
代码如下:
这样,就可以进行动态查询
有关详细说明,请访问here
相关问题 更多 >
编程相关推荐